-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongoose.js
74 lines (63 loc) · 2.32 KB
/
mongoose.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
'use strict';
var mongoose = require('mongoose');
const MAILER_MONGO_USER = process.env.MAILER_MONGO_USER || "";
const MAILER_MONGO_PASSWORD = process.env.MAILER_MONGO_PASSWORD || "";
const MAILER_MONGO_DATABASE = process.env.MAILER_MONGO_DATABASE || "mails";
const MAILER_MONGO_ADDR = process.env.MONGO_PORT_27017_TCP_ADDR || "localhost";
const MAILER_MONGO_PORT = process.env.MONGO_PORT_27017_TCP_PORT || "27017";
const MAILER_MONGO_HOST = `${MAILER_MONGO_ADDR}:${MAILER_MONGO_PORT}`;
const URL = buildMongoUrl(MAILER_MONGO_USER, MAILER_MONGO_PASSWORD, MAILER_MONGO_DATABASE, MAILER_MONGO_HOST);
// Build connection URL dependent on whether a user is specified or not
function buildMongoUrl(user, password, database, host) {
if (user == "") {
return `mongodb://${host}/${database}`;
} else {
return `mongodb://${user}:${password}@${host}/${database}`;
}
}
/**
* Code in this File is taken from http://stackoverflow.com/a/33139673
*
* Created By: Gil SH (https://stackoverflow.com/users/880223/gil-sh)
* License is cc by-sa 3.0
*/
var db = mongoose.connection;
var lastReconnectAttempt; //saves the timestamp of the last reconnect attempt
var opt = {
// user: 'admin',
// pass: 'pass',
// auth: {
// authdb: 'admin'
// },
autoReconnect: true,
useNewUrlParser: true
};
console.log('mongoose connect', URL, opt);
mongoose.createConnection(URL, opt);
db.on('error', function (error) {
console.error('Error in MongoDb connection: ' + error);
mongoose.disconnect();
});
db.on('disconnected', function () {
console.log('MongoDB disconnected!');
var now = new Date().getTime();
// check if the last reconnection attempt was too early
if (lastReconnectAttempt && now - lastReconnectAttempt < 5000) {
// if it does, delay the next attempt
var delay = 5000 - (now - lastReconnectAttempt);
console.log('reconnecting to MongoDB in ' + delay + "mills");
setTimeout(function () {
console.log('reconnecting to MongoDB');
lastReconnectAttempt = new Date().getTime();
mongoose.createConnection(URL, opt);
}, delay);
}
else {
console.log('reconnecting to MongoDB');
lastReconnectAttempt = now;
mongoose.createConnection(URL, opt);
}
});
module.exports = {
mongoose: mongoose
};