forked from openhab/openhab-cloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoconnect.js
64 lines (55 loc) · 1.79 KB
/
mongoconnect.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
var logger = require('../logger.js');
/**
* @param {System} system
* @constructor
*/
function MongoConnect(system) {
this.system = system;
}
/**
* Takes the mongoose object and tries to connect it with the configured database of the system object provided to the
* constructor of this object.
*
* The optional callback parameter can be used to pass a callback to the mongoose.connect function.
*
* @param mongoose
* @param callback
*/
MongoConnect.prototype.connect = function (mongoose, callback) {
if (typeof callback !== 'function') {
callback = this.defaultCallback;
}
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
logger.info('opneHAB-cloud: Trying to connect to mongodb at: ' + this.getMongoUri());
mongoose.connect(this.getMongoUri(), callback);
};
/**
* The callback used in #connect, if no callback was provided.
*
* @param error
* @private
*/
MongoConnect.prototype.defaultCallback = function (error) {
if (error) {
logger.error('openHAB-cloud: Error while connecting from openHAB-cloud to mongodb: ' + error);
logger.error('openHAB-cloud: Stopping openHAB-cloud due to error with mongodb');
process.exit(1);
}
logger.info('openHAB-cloud: Successfully connected to mongodb');
};
/**
* Returns the connection string to use to connect to mongodb.
*
* @return {string}
* @private
*/
MongoConnect.prototype.getMongoUri = function () {
var mongoUri = 'mongodb://';
if (this.system.hasDbCredentials())
mongoUri += this.system.getDbUser() + ':' + this.system.getDbPass() + '@';
mongoUri += this.system.getDbHostsString();
return mongoUri + '/' + this.system.getDbName() + '?poolSize=50';
};
module.exports = MongoConnect;