2017-06-19 18:37:35 +02:00
|
|
|
const fs = require('fs');
|
|
|
|
const path = require('path');
|
|
|
|
const Sequelize = require('sequelize');
|
|
|
|
const basename = path.basename(module.filename);
|
|
|
|
const config = require('config');
|
|
|
|
const db = {};
|
2017-06-19 22:22:06 +02:00
|
|
|
const logger = require('winston');
|
2017-06-15 20:15:13 +02:00
|
|
|
|
2017-06-19 18:37:35 +02:00
|
|
|
const connectionUri = config.get('Database.MySqlConnectionUri');
|
2017-06-19 22:22:06 +02:00
|
|
|
const sequelize = new Sequelize(connectionUri, {
|
|
|
|
logging: false,
|
|
|
|
});
|
2017-06-15 20:15:13 +02:00
|
|
|
|
|
|
|
sequelize
|
|
|
|
.authenticate()
|
|
|
|
.then(() => {
|
2017-06-19 22:22:06 +02:00
|
|
|
logger.info('Sequelize has has been established mysql connection successfully.');
|
2017-06-15 20:15:13 +02:00
|
|
|
})
|
|
|
|
.catch(err => {
|
2017-06-19 22:22:06 +02:00
|
|
|
logger.error('Sequelize was nable to connect to the database:', err);
|
2017-06-19 18:37:35 +02:00
|
|
|
});
|
2017-06-15 20:15:13 +02:00
|
|
|
|
2017-06-17 22:51:30 +02:00
|
|
|
fs.readdirSync(__dirname).filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js').forEach(file => {
|
2017-06-19 18:37:35 +02:00
|
|
|
const model = sequelize['import'](path.join(__dirname, file));
|
|
|
|
db[model.name] = model;
|
|
|
|
});
|
2017-06-17 22:51:30 +02:00
|
|
|
|
|
|
|
Object.keys(db).forEach(modelName => {
|
2017-06-15 20:15:13 +02:00
|
|
|
if (db[modelName].associate) {
|
2017-06-19 18:37:35 +02:00
|
|
|
db[modelName].associate(db);
|
2017-06-15 20:15:13 +02:00
|
|
|
}
|
2017-06-19 18:37:35 +02:00
|
|
|
});
|
2017-06-15 20:15:13 +02:00
|
|
|
|
2017-06-19 18:37:35 +02:00
|
|
|
db.sequelize = sequelize;
|
|
|
|
db.Sequelize = Sequelize;
|
2017-06-15 20:15:13 +02:00
|
|
|
|
2017-06-19 18:37:35 +02:00
|
|
|
module.exports = db;
|