76 lines
2.6 KiB
JavaScript
76 lines
2.6 KiB
JavaScript
module.exports = function (debugMode = false) {
|
|
const
|
|
debug = require('debug')('agm:db'),
|
|
mongoose = require('mongoose'),
|
|
env = require('../env'),
|
|
utils = require('../utils');
|
|
|
|
// Our custom middleware
|
|
mongoose.Promise = global.Promise; // Disable Promise depreciated warning
|
|
|
|
const ops = {
|
|
connectTimeoutMS: 40000,
|
|
// TCP Connection timeout setting. Best = 2-3X time of longest operation (30 minutes)
|
|
socketTimeoutMS: 30 * 60 * 1000,
|
|
// The number of milliseconds to wait before initiating keepAlive on the TCP socket.
|
|
keepAlive: true, keepAliveInitialDelay: 30000,
|
|
// Auto creation of indexes set to false for DEBUG and true only for dev for better performace in Production invironment
|
|
autoIndex: !(env.PRODUCTION),
|
|
maxPoolSize: env.DB_MAX_POOLSIZE, // Default 100 from MDB 5.0.x
|
|
family: 4,
|
|
}
|
|
|
|
let _uri = `@${env.DB_HOSTS}/${env.DB_NAME}`;
|
|
|
|
if (env.DB_REPLSET)
|
|
ops.replicaSet = env.DB_REPLSET
|
|
|
|
if (env.DB_USE_TLS) {
|
|
ops.tls = true; ops.sslValidate = true;
|
|
ops.tlsCAFile = env.DB_TLS_CA_FILE;
|
|
ops.tlsCertificateKeyFile = env.DB_TLS_CERT_FILE;
|
|
}
|
|
ops.directConnection = true;
|
|
|
|
if (env.DB_USE_X509) {
|
|
ops.authMechanism = 'MONGODB-X509';
|
|
_uri = `mongodb://${encodeURIComponent(env.DB_USR)}` + _uri;
|
|
} else {
|
|
_uri = `mongodb://${env.DB_USR}:${env.DB_PWD}` + _uri;
|
|
ops.authSource = env.DB_AUTH_SOURCE || env.DB_NAME
|
|
ops.authMechanism = 'SCRAM-SHA-1'
|
|
}
|
|
|
|
mongoose.set('strictQuery', false);
|
|
mongoose.set('strictPopulate', false);
|
|
mongoose.set('bufferCommands', false); // Disable buffering globally
|
|
|
|
mongoose.connect(_uri, ops);
|
|
|
|
mongoose.connection.on('disconnected', () => { debug('-> MongoDB lost/closed connection'); });
|
|
mongoose.connection.on('reconnect', () => { debug('-> MongoDB reconnected'); });
|
|
mongoose.connection.on('connected', () => { debug('-> MongoDB connected'); });
|
|
mongoose.connection.on('open', () => { debug('-> MongoDB open'); });
|
|
mongoose.connection.on('reconnectFailed', () => { debug('-> MongoDB gave up reconnecting'); });
|
|
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection errors:'));
|
|
|
|
if (debugMode) mongoose.set('debug', true);
|
|
|
|
function postExit() {
|
|
if (mongoose.connection) {
|
|
mongoose.connection.close(() => {
|
|
debug('Mongoose default connection disconnected through app termination');
|
|
process.exit(0);
|
|
});
|
|
} else {
|
|
process.exit(0);
|
|
}
|
|
}
|
|
// If the Node process ends, close the Mongoose connection
|
|
process.on('SIGINT', function () { // Windows
|
|
postExit();
|
|
});
|
|
|
|
return mongoose.connection;
|
|
}
|