2020-04-12 11:11:06 +00:00
|
|
|
import { Sequelize } from 'sequelize-typescript'
|
2020-04-12 11:52:50 +00:00
|
|
|
import { cloneDeep } from 'lodash'
|
2020-06-02 11:48:38 +00:00
|
|
|
import * as path from 'path'
|
2020-04-12 11:11:06 +00:00
|
|
|
import { Author } from './author'
|
|
|
|
import { Note } from './note'
|
|
|
|
import { Revision } from './revision'
|
|
|
|
import { Temp } from './temp'
|
|
|
|
import { User } from './user'
|
|
|
|
import { logger } from '../logger'
|
|
|
|
import { config } from '../config'
|
2020-06-02 11:48:38 +00:00
|
|
|
import Umzug from 'umzug'
|
|
|
|
import SequelizeTypes from 'sequelize'
|
2020-04-12 11:11:06 +00:00
|
|
|
|
|
|
|
const dbconfig = cloneDeep(config.db)
|
2020-04-12 11:52:50 +00:00
|
|
|
dbconfig.logging = config.debug ? (data): void => {
|
2019-04-12 04:05:32 +00:00
|
|
|
logger.info(data)
|
|
|
|
} : false
|
2016-12-12 02:18:12 +00:00
|
|
|
|
2020-04-12 11:52:50 +00:00
|
|
|
export let sequelize: Sequelize
|
2016-12-22 05:23:17 +00:00
|
|
|
|
2016-12-22 11:42:00 +00:00
|
|
|
// Heroku specific
|
2018-03-07 14:17:35 +00:00
|
|
|
if (config.dbURL) {
|
|
|
|
sequelize = new Sequelize(config.dbURL, dbconfig)
|
2017-03-08 10:45:51 +00:00
|
|
|
} else {
|
|
|
|
sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password, dbconfig)
|
|
|
|
}
|
2016-04-20 10:03:55 +00:00
|
|
|
|
2020-06-02 11:48:38 +00:00
|
|
|
const umzug = new Umzug({
|
|
|
|
migrations: {
|
|
|
|
path: path.resolve(__dirname, '..', 'migrations'),
|
|
|
|
params: [
|
|
|
|
sequelize.getQueryInterface(),
|
|
|
|
SequelizeTypes
|
|
|
|
]
|
|
|
|
},
|
|
|
|
// Required wrapper function required to prevent winstion issue
|
|
|
|
// https://github.com/winstonjs/winston/issues/1577
|
2020-08-04 22:09:19 +00:00
|
|
|
logging: (message): void => {
|
2020-06-02 11:48:38 +00:00
|
|
|
logger.info(message)
|
|
|
|
},
|
|
|
|
storage: 'sequelize',
|
|
|
|
storageOptions: {
|
|
|
|
sequelize: sequelize
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2020-08-04 22:09:19 +00:00
|
|
|
export async function runMigrations (): Promise<void> {
|
2020-06-02 11:48:38 +00:00
|
|
|
// checks migrations and run them if they are not already applied
|
|
|
|
// exit in case of unsuccessful migrations
|
|
|
|
await umzug.up().catch(error => {
|
|
|
|
logger.error(error)
|
|
|
|
logger.error('Database migration failed. Exiting…')
|
|
|
|
process.exit(1)
|
|
|
|
})
|
|
|
|
logger.info('All migrations performed successfully')
|
|
|
|
}
|
|
|
|
|
2020-04-12 11:11:06 +00:00
|
|
|
sequelize.addModels([Author, Note, Revision, Temp, User])
|
2020-04-11 10:13:37 +00:00
|
|
|
|
2020-04-12 11:11:06 +00:00
|
|
|
export { Author, Note, Revision, Temp, User }
|