UNPKG

1.89 kBJavaScriptView Raw
1"use strict";
2
3var fs = require("fs"),
4 path = require("path"),
5 exists = require('fs-exists-sync'),
6 mongoose = require('mongoose'),
7 events = require('../events/index.js'),
8 middleware = require('../middleware/index.js'),
9 paths = require('../configs/paths'),
10 config = require('../configs/config');
11
12module.exports = class {
13
14 constructor() {
15 this.middleware = new middleware();
16 this.events = new events();
17
18 return this.connect();
19 }
20
21 connect() {
22 if (exists(paths.app.models)) {
23 var dbconfig = config('database_config') ? JSON.parse(config('database_config')) : null;
24
25 if (config('database_connect')) {
26 mongoose.connect(JSON.parse(config('database_connect')), dbconfig);
27 } else {
28 var host = config('database_host') || config('database_hostname'),
29 name = config('database_name')
30
31 mongoose.connect(`mongodb://${host}/${name}`, dbconfig);
32 }
33
34 mongoose.events = this.events;
35 mongoose.logger = require('../logs')();
36
37 var models = [];
38
39 fs.readdirSync(paths.app.models)
40 .filter((file) => {
41 return (file.indexOf(".") !== 0 && file.indexOf(".sequelize.js") == -1);
42 })
43 .forEach((file) => {
44 var model = require(path.join(paths.app.models, file))(mongoose);
45
46 if (typeof model == "object") {
47 var schema = (model.schema) ? model.schema : model;
48
49 if (model.name) {
50 models[model.name] = mongoose.model(model.name, this.middleware.emit("mongoose", model));
51 }
52 }
53 });
54
55 return models;
56 }
57 return null;
58 }
59
60}