forked from FlexLabs/Dyno-datafactory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
78 lines (60 loc) · 1.64 KB
/
Copy pathindex.js
File metadata and controls
78 lines (60 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict';
const fs = require('fs');
const path = require('path');
const mongoose = require('mongoose');
const Logger = require('./logger');
const basename = path.basename(module.filename);
const modelPath = path.join(__dirname, 'models');
class DataFactory {
constructor(options) {
this.logger = new Logger(options.logger || {});
this._models = {};
this.logger.info('Connecting to mongodb...');
mongoose.Promise = global.Promise;
const connectOpts = {
poolSize: 5,
autoReconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 5000,
keepAlive: 120,
connectTimeoutMS: 30000,
promiseLibrary: global.Promise,
useCreateIndex: true,
useNewUrlParser: true,
};
// if (!options.disableReplica) {
// connectOpts.replicaSet = 'dyno';
// }
mongoose.connect(options.dbString, connectOpts);
const connection = mongoose.connection;
connection.on('error', this.logger.error);
connection.once('open', () => this.logger.info('Connected to mongo.'));
fs
.readdirSync(modelPath)
.filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))
.forEach(file => {
const model = require(path.join(modelPath, file));
this.registerModel(model);
});
}
get models() {
return this._models;
}
get mongoose() {
return mongoose;
}
get connection() {
return mongoose.connection;
}
collection(...args) {
return mongoose.connection.collection(...args);
}
get Schema() {
return mongoose.Schema;
}
registerModel({name, schema}) {
const model = mongoose.model(name, schema);
this._models[model.modelName] = model;
}
}
module.exports = DataFactory;