Created
May 13, 2020 19:23
-
-
Save psi-4ward/95877c8aa87602e7e40d29c4513984e5 to your computer and use it in GitHub Desktop.
sequelize-typescript database migration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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