@athenna/database
Version:
The Athenna database handler for SQL/NoSQL.
70 lines (69 loc) • 2.41 kB
JavaScript
/**
* @athenna/database
*
* (c) João Lenon <lenon@athenna.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { debug } from '#src/debug';
import { Module, Path } from '@athenna/common';
import { DatabaseImpl } from '#src/database/DatabaseImpl';
import { ConnectionFactory } from '#src/factories/ConnectionFactory';
export class MigrationSource {
constructor(connection) {
this.connection = null;
this.connection = connection;
}
/**
* Verify if migration is able to run by connection.
*/
isAbleToRun(migration) {
return migration.connection() === this.connection;
}
/**
* Get all the migrations from migrations path and import
* as modules. This method will be used by "getMigration"
* method later to get the migrations "up"/"down" methods.
*/
async getMigrations() {
const migrations = [];
const files = await Module.getAllJSFilesFrom(Path.migrations());
for (const file of files) {
const Migration = await Module.getFrom(file.path);
if (this.isAbleToRun(Migration)) {
migrations.push({ name: file.base, Migration });
}
}
return migrations;
}
/**
* Get the migration name that will be used to set in
* migrations table.
*/
getMigrationName(source) {
return source.name;
}
/**
* Creates a new migration instance and return the up/down
* methods in object.
*/
async getMigration(source) {
const migration = new source.Migration();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const connection = source.Migration.connection();
const database = new DatabaseImpl({ connect: false });
debug('configuring database connection %s to run migration %s', connection, source.Migration.name);
database.connectionName = connection;
database.driver = ConnectionFactory.fabricate(connection);
const bind = (method, knex) => {
database.driver = database.driver.setClient(knex);
return migration[method].bind(migration)(database);
};
return {
up: knex => bind('up', knex),
down: knex => bind('down', knex)
};
}
}