Skip to content

Instantly share code, notes, and snippets.

@psi-4ward
Created May 13, 2020 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psi-4ward/95877c8aa87602e7e40d29c4513984e5 to your computer and use it in GitHub Desktop.
Save psi-4ward/95877c8aa87602e7e40d29c4513984e5 to your computer and use it in GitHub Desktop.
sequelize-typescript database migration
/**
* Database migration helper using Umzug
* supports TypeScript (ts-node) and JS
*
* Usage:
* * With ts-node: npx ts-node src/db-migrate.ts
* * or after transpile: node src/db-migrate.js
*
* Params:
* * down: Downgrade the last migration
*/
import { Sequelize } from 'sequelize-typescript';
import { ormConfig } from './orm.config';
import { Umzug } from 'umzug';
import * as path from "path";
const sequelize = new Sequelize(ormConfig);
sequelize.addModels([
// accept all *.entity.ts and *.entity.js files as models
path.resolve(__dirname, 'models', '*.entity.{ts,js}')
]);
const umzug = new Umzug({
migrations: {
path: path.resolve(__dirname, 'db-migrations'),
params: [sequelize.getQueryInterface()],
// only allow one dot in migrations files (ie to exclude .d.ts)
pattern: /^[^\.]+\.(j|t)s$/,
// rewrite filesuffixes always to ".js" for ts-node support
nameFormatter: fileWithPath => {
const filename = path.basename(fileWithPath);
return filename.replace(/\.ts$/, '.js');
}
},
storage: 'sequelize',
storageOptions: { sequelize }
});
( async () => {
// Checks migrations and run them if they are not already applied. To keep
// track of the executed migrations, a table (and sequelize model) called SequelizeMeta
// will be automatically created (if it doesn't exist already) and parsed.
let ok = true;
try {
if (!process.argv.includes('down')) {
const applied = await umzug.up();
if(applied.length === 0) {
console.log('Database is up to date.')
} else {
applied.forEach(m => console.log('Applied migration', m.file));
}
} else {
const reverted = await umzug.down();
reverted.forEach(m => console.log('Reverted migration', m.file));
}
} catch (e) {
ok = false;
console.error('Error:', e.message);
}
await sequelize.close();
process.exit(ok ? 0 : 1);
} )();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment