-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathmongo.js
53 lines (48 loc) · 1.46 KB
/
mongo.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
var EventEmitter = require('events').EventEmitter;
var log = require('debug')('sourced-repo-mongo');
var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var url = require('url');
var util = require('util');
function Mongo () {
this.client = null;
this.db = null;
EventEmitter.call(this);
}
util.inherits(Mongo, EventEmitter);
Mongo.prototype.connect = function connect (mongoUrl, database, options = {
useNewUrlParser: true,
useUnifiedTopology: true
}) {
var self = this;
return new Promise((resolve, reject) => {
self.on('connected', (db) => {
resolve(db)
})
self.on('error', (err) => {
reject(err)
})
MongoClient.connect(mongoUrl, options, function (err, client) {
if (err) {
log('✗ MongoDB Connection Error. Please make sure MongoDB is running: ', err);
self.emit('error', err);
}
var expanded = url.parse(mongoUrl);
// replica set url does not include db, it is passed in separately
var dbName = database || expanded.pathname.replace('/', '');
self.client = client;
var db = client.db(dbName);
self.db = db;
log('initialized connection to mongo at %s', mongoUrl);
self.emit('connected', db);
});
})
};
Mongo.prototype.close = function (cb) {
log('closing sourced mongo connection');
return this.client.close((err) => {
log('closed sourced mongo connection');
cb(err)
});
};
module.exports = new Mongo();