UNPKG

1.78 kBJavaScriptView Raw
1// Mongoose DB Configuration and init
2'use strict';
3
4const cluster = require('cluster');
5const chalk = require('chalk');
6const config = require('./config')();
7const glob = require('glob');
8const winston = require('winston');
9
10// Print Once
11function _printOnce(){
12 return cluster.isMaster || (cluster.worker && cluster.worker.id==1);
13}
14
15// Connect to DB
16function connect(mongoose, options){
17 if(mongoose.connection.readyState==1 || mongoose.connection.readyState==2){
18 return;
19 }
20
21 var Server = config.get().db.server || 'localhost';
22 var DBName = config.get().db.name || 'mio-demo';
23
24 if(options && options.server && options.name){
25 Server = options.server;
26 DBName = options.name;
27 }
28
29 if(_printOnce()){
30 winston.info('-'.repeat(70));
31 winston.info('Using DataBase:', chalk.blue(Server,'/',DBName));
32 }
33
34 mongoose.connect('mongodb://'+Server+'/'+DBName, (err) => {
35 if(err) {
36 winston.error('Error with DataBase', DBName, ':', err);
37 process.exit();
38 }
39 });
40
41 if(!global.mio.mongo){
42 global.mio.mongo = {
43 mongoose: mongoose,
44 connection: mongoose.connection
45 };
46 }
47}
48
49// Load static data models
50function loadModels(){
51 var files = glob.sync(global.mio.appPath+'/modules/*/models/*.js');
52 var modulesNames = [];
53 for (var i = 0; i < files.length; i++) {
54 var moduleName = files[i].split('/')[1];
55 try {
56 require(files[i]);
57 if(modulesNames.indexOf(moduleName) == -1) modulesNames.push(moduleName);
58 } catch (err) {
59 winston.error('Can\'t load models for ', moduleName);
60 winston.error(err);
61 }
62 }
63}
64
65// Magic init
66function init(mongoose, options){
67 connect(mongoose, options);
68 loadModels(mongoose);
69}
70
71module.exports = {
72 init: init,
73 connect: connect,
74 loadModels: loadModels
75};