1 |
|
2 | 'use strict';
|
3 |
|
4 | const cluster = require('cluster');
|
5 | const chalk = require('chalk');
|
6 | const config = require('./config')();
|
7 | const glob = require('glob');
|
8 | const winston = require('winston');
|
9 |
|
10 |
|
11 | function _printOnce(){
|
12 | return cluster.isMaster || (cluster.worker && cluster.worker.id==1);
|
13 | }
|
14 |
|
15 |
|
16 | function 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 |
|
50 | function 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 |
|
66 | function init(mongoose, options){
|
67 | connect(mongoose, options);
|
68 | loadModels(mongoose);
|
69 | }
|
70 |
|
71 | module.exports = {
|
72 | init: init,
|
73 | connect: connect,
|
74 | loadModels: loadModels
|
75 | };
|