UNPKG

1.69 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
10module.exports = class {
11
12 constructor(config, paths) {
13 if (!config) {
14 return null;
15 }
16
17 this.middleware = new middleware(config, paths);
18 this.events = new events(config, paths);
19
20 return this.connect(config);
21 }
22
23 connect(config) {
24 if (exists(paths.app.models)) {
25
26 if (config.connect) {
27 mongoose.connect(config.connect, config.config);
28 }
29 else {
30 mongoose.connect(`mongodb://${config.host}/${config.name}`, config.config);
31 }
32
33 mongoose.events = this.events;
34 mongoose.logger = require('../logs')(config, paths);
35
36 var models = [];
37
38 fs.readdirSync(paths.app.models)
39 .filter((file) => {
40 return (file.indexOf(".") !== 0 && file.indexOf(".sequelize.js") == -1);
41 })
42 .forEach((file) => {
43 var model = require(path.join(paths.app.models, file))(mongoose);
44 if (typeof model == "object") {
45 var schema = (model.schema) ? model.schema : model;
46
47 if (model.name) {
48 models[model.name] = mongoose.model(model.name, this.middleware.emit("mongoose", model));
49 }
50 }
51 });
52
53 return models;
54 }
55 return null;
56 }
57
58}