flame/db/index.js

52 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2021-10-05 10:29:17 +00:00
const { Sequelize } = require('sequelize');
const { join } = require('path');
const Umzug = require('umzug');
2021-11-13 22:28:43 +00:00
// Utils
const backupDB = require('./utils/backupDb');
2021-10-05 10:29:17 +00:00
const Logger = require('../utils/Logger');
const logger = new Logger();
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: './data/db.sqlite',
logging: false,
});
const umzug = new Umzug({
migrations: {
path: join(__dirname, './migrations'),
params: [sequelize.getQueryInterface()],
},
storage: 'sequelize',
storageOptions: {
sequelize,
},
});
const connectDB = async () => {
try {
backupDB();
2021-10-05 10:29:17 +00:00
await sequelize.authenticate();
2021-11-13 22:28:43 +00:00
// execute all pending migrations
2021-10-05 10:29:17 +00:00
const pendingMigrations = await umzug.pending();
if (pendingMigrations.length > 0) {
logger.log('Executing pending migrations');
await umzug.up();
}
2021-11-13 22:28:43 +00:00
logger.log('Connected to database');
2021-10-05 10:29:17 +00:00
} catch (error) {
logger.log(`Unable to connect to the database: ${error.message}`, 'ERROR');
process.exit(1);
}
};
module.exports = {
connectDB,
sequelize,
};