greenlock-store-sequelize.js/db/index.js

50 lines
1.1 KiB
JavaScript
Raw Normal View History

'use strict';
var fs = require('fs');
var path = require('path');
var basename = path.basename(__filename);
var Sequelize = require('sequelize');
var sync = require('../sync.js');
module.exports = function (config) {
var db = {};
db.Sequelize = Sequelize;
if (!config) {
config = {
dialect: "sqlite",
storage: "./db.sqlite"
};
}
if (config.use_env_variable) {
db.sequelize = new db.Sequelize(process.env[config.use_env_variable], config);
2019-04-10 14:11:38 +00:00
}
else {
db.sequelize = new db.Sequelize(config.database, config.username, config.password, config);
}
2019-04-10 14:11:38 +00:00
fs.readdirSync(__dirname).filter(function (file) {
return ('.' !== file[0]) && (file !== basename) && (file.slice(-3) === '.js');
}).forEach(function (file) {
var model = db.sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
var synced = false;
if (!synced) {
return sync(db).then(function () {
synced = true;
return db;
});
}
return Promise.resolve(db);
};