83 lines
2.4 KiB
JavaScript
83 lines
2.4 KiB
JavaScript
'use strict';
|
|
|
|
module.exports = function () {
|
|
var db = {};
|
|
|
|
const config = require('config');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const nanoid = require('nanoid');
|
|
|
|
var dbOptions = {
|
|
db: db,
|
|
generateUniqueId: (customIdSize) => {
|
|
var idSize = customIdSize || 11;
|
|
return nanoid(idSize); //=> "hsCc0ocrXkc"
|
|
}
|
|
};
|
|
|
|
dbOptions.Sequelize = require('sequelize');
|
|
|
|
dbOptions.sequelize = new dbOptions.Sequelize(config.get('database'));
|
|
|
|
// Load all the models...
|
|
var modelDir = path.join(__dirname, './models/');
|
|
fs.readdirSync(modelDir)
|
|
.filter(file => {
|
|
return (file.indexOf('.') !== 0) && (file !== "index.js") && (file.slice(-3) === '.js');
|
|
})
|
|
.forEach(file => {
|
|
// const model = sequelize['import'](path.join(modelDir, file));
|
|
const model = require(path.join(modelDir, file))(dbOptions.sequelize, dbOptions.Sequelize, dbOptions);
|
|
|
|
// Format the Model Name like we have for this project...
|
|
var modelName = model.name;
|
|
modelName = modelName.replace(modelName[0], modelName[0].toUpperCase());
|
|
|
|
// Add model to the db...
|
|
db[modelName] = model;
|
|
});
|
|
|
|
// Time for the associations...
|
|
Object.keys(db).forEach(modelName => {
|
|
if (db[modelName].associate) {
|
|
db[modelName].associate(db);
|
|
}
|
|
});
|
|
|
|
db.LoadDB = () => {
|
|
db.Sequelize = dbOptions.Sequelize;
|
|
db.sequelize = dbOptions.sequelize;
|
|
|
|
return new Promise((resolve, reject) => {
|
|
dbOptions.sequelize.sync()
|
|
.then(() => {
|
|
resolve(db);
|
|
}).catch(error => {
|
|
// Do the things...
|
|
reject(error);
|
|
console.error('Unable to connect to the database:', error);
|
|
})
|
|
})
|
|
}
|
|
|
|
db.updateDatabaseFromModels = () => {
|
|
return new Promise((resolve, reject) => {
|
|
dbOptions.sequelize.sync({
|
|
alter: true
|
|
})
|
|
.then(() => {
|
|
resolve(true);
|
|
console.log("DB update successful.");
|
|
})
|
|
.catch(error => {
|
|
// Do the things...
|
|
reject(error);
|
|
console.error('Unable to connect to the database:', error);
|
|
})
|
|
})
|
|
}
|
|
return db;
|
|
};
|
|
|