/** * * Copyright (c) 2016, Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ "use strict"; /** * This class will instantiate the ORM, load in the models, call the method * to create db connections, test the connection, then create the tables and * relationships if not present */ const fs = require('fs'), path = require('path'), Sequelize = require('sequelize'), config = require('config'); function init() { const db = { sequelize: new Sequelize(config.get("db.host"), config.get("db.options")) }; return new Promise(function(resolve, reject) { console.log("DB initialization beginning. DB access will block."); let models = []; /* Load models */ fs.readdirSync(__dirname).forEach(function (file) { if (file == "." || file == ".." || file == "index.js") { return; } let model = db.sequelize.import(path.join(__dirname, file)); db[model.name] = model; models.push(model); }); /* After all the models are loaded, associate any that need it */ models.forEach(function (model) { if (model.associate) { model.associate(db); } }); return db.sequelize.authenticate().then(function () { console.log("Connection established successfully with DB."); return db.sequelize.sync({ force: false }).then(function () { console.log("DB relationships successfully mapped. DB access unblocked."); return resolve(db); }); }).catch(function (error) { console.log("ERROR: Failed to authenticate with DB"); console.log("ERROR: " + JSON.stringify(config.get("db"), null, 2)); console.log(error); return reject(error); }); }); } module.exports = init();