/
connector.js
80 lines (59 loc) · 2.09 KB
/
connector.js
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
79
80
'use strict';
const Hoek = require('@hapi/hoek');
const Mongoose = require('mongoose');
const EventEmitter = require('events').EventEmitter;
exports = module.exports = class Connector extends EventEmitter {
constructor({ uri, config = {}, logger }) {
super();
Hoek.assert(typeof uri === 'string', new Error('uri must be a string'));
Hoek.assert(uri !== '', new Error('uri is required'));
this.mongoose = Mongoose;
this.logger = logger;
this.uri = uri;
this.config = Object.assign({ useNewUrlParser: true }, config);
this.models = {};
this.connection = this.connect();
this.addListeners();
}
log(message = '') {
if (typeof this.logger === 'function') {
this.logger(message);
}
}
connect() {
return this.mongoose.createConnection(this.uri, this.config);
}
addListeners() {
this.connection
.on('connected', () => {
this.log('Connection to database ready');
this.emit('ready', `✔ Connected to ${this.uri}`);
})
.on('error', (error) => {
this.log(`Unable to connect to database: ${error.message}`);
this.emit('error', error);
})
.on('open', () => {
this.emit('open', 'Connection to database opened');
})
.on('close', () => {
this.log('Connection to database closed');
this.emit('close', 'Connection to database closed');
})
.on('disconnected', () => {
this.log('Connection to database disconnected');
this.emit('disconnected', 'Database disconnected');
});
}
setModels(schemas = {}) {
for (const key in schemas) {
this.models[key] = this.connection.model(key, schemas[key]);
}
}
getModel(name) {
if (!this.models.hasOwnProperty(name)) {
throw new Error(`Model '${name}' does not exist`);
}
return this.models[name];
}
};