app2-api/core/models.js

59 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-04-15 10:13:17 +00:00
const glob = require('glob');
const path = require('path');
const Sequelize = require('sequelize');
2019-04-15 15:58:58 +00:00
const config = require('../config');
const log = require('./logger');
2019-04-15 10:13:17 +00:00
const modulesDir = path.resolve(__dirname + '/../modules/')
const globOptions = {
cwd: modulesDir,
nocase: true,
nodir: true,
absolute: true,
}
2019-04-15 15:58:58 +00:00
log.info('Configurando DB.');
2019-10-21 09:36:37 +00:00
const db = {};
2019-04-15 15:58:58 +00:00
const sequelize = new Sequelize(
config.database.database,
config.database.username,
config.database.password,
config.database, {
dialect: 'mysql',
2019-07-28 20:08:15 +00:00
operatorAliases: false,
2019-10-31 11:11:28 +00:00
logging: config.debug,
2019-11-02 22:16:58 +00:00
define: {
charset: 'utf8',
collate: 'utf8_general_ci',
},
2019-10-31 11:11:28 +00:00
pool: {
max: 140,
min: 0,
idle: 10000
}
2019-04-15 15:58:58 +00:00
}
);
2019-10-21 09:36:37 +00:00
try {
db.sequelize = sequelize;
db.Sequelize = Sequelize;
glob.sync("**/*.model.js", globOptions)
.forEach(function (file) {
var model = sequelize.import(file);
log.info('Loading "' + model.name + '" model.');
db[model.name] = model;
});
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
2019-04-15 10:13:17 +00:00
});
2019-10-21 09:36:37 +00:00
} catch (error) {
console.error(error);
}
2019-04-15 10:13:17 +00:00
2019-04-15 15:58:58 +00:00
module.exports = db;