@smallprod/models
Version:
72 lines (71 loc) • 2.97 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const altertable_1 = __importDefault(require("./types/altertable"));
const createtable_1 = __importDefault(require("./types/createtable"));
const droptable_1 = __importDefault(require("./types/droptable"));
const migration_entity_1 = __importDefault(require("../entities/migration.entity"));
const seed_1 = __importDefault(require("./types/seed"));
class Migration {
constructor(migrationName, type, migrations = []) {
this.migrations = [];
this.createTable = (name) => {
const createTableMigration = new createtable_1.default(name);
this.migrations.push(createTableMigration);
return createTableMigration;
};
this.dropTable = (name) => {
const dropTableMigration = new droptable_1.default(name);
this.migrations.push(dropTableMigration);
return dropTableMigration;
};
this.alterTable = (name) => {
const alterTableMigration = new altertable_1.default(name);
this.migrations.push(alterTableMigration);
return alterTableMigration;
};
this.seedTable = (tableName) => {
const seedTableMigration = new seed_1.default(tableName);
this.migrations.push(seedTableMigration);
return seedTableMigration;
};
this.findByTableName = (tableName) => {
return this.migrations.filter((m) => m.tableName === tableName && m.type !== 'seed');
};
this.execute = async (db, silent) => {
if (!(await db.startTransaction())) {
console.error('Transaction cannot be started');
console.log('\x1b[31m → Failure\x1b[0m');
throw new Error();
return;
}
try {
await this.migrations.reduce(async (prev, cur) => {
await prev;
await cur.execute(db);
}, Promise.resolve());
if (this.type === 'up') {
await migration_entity_1.default.create(db, this.migrationName);
}
else {
await migration_entity_1.default.delete(db, this.migrationName);
}
await db.commit();
if (!silent)
console.log('\x1b[32m → Success\x1b[0m');
}
catch (error) {
await db.rollback();
console.error(error);
console.log('\x1b[31m → Failure\x1b[0m');
throw new Error();
}
};
this.migrationName = migrationName;
this.type = type;
this.migrations = migrations;
}
}
exports.default = Migration;