Skip to content

Instantly share code, notes, and snippets.

@abuzarhamza
Created October 23, 2018 18:26
Show Gist options
  • Save abuzarhamza/922a48612bb2e4d56c90533d02927f42 to your computer and use it in GitHub Desktop.
Save abuzarhamza/922a48612bb2e4d56c90533d02927f42 to your computer and use it in GitHub Desktop.
dbConnection
const mongoose = require('mongoose');
const errorResp = function (err) {
return {
message: 'Unable to connect to DB',
errorCode: 40
};
};
// Export DB Connection function
mongoose.Promise = global.Promise;
module.exports = function (options, callback) {
if (global && global.cachedConnection && global.cachedConnection.readyState && global.cachedConnection.readyState === 1) {
return global.connectionPromise;
} else {
console.log('No connection Found. Creating connection !!!');
try {
let connectionPromise = mongoose.connect(fooURL, {
useMongoClient: true,
poolSize: (options && options.poolSize) ? options.poolSize : 2,
connectTimeoutMS: 30000,
socketTimeoutMS: 30000,
keepAlive: 120
});
global.connectionPromise = connectionPromise;
connectionPromise.then((db) => {
if (mongoose.connection) {
let connection = mongoose.connection;
global.cachedConnection = connection;
connection.on('error', function (err) {
global.cachedConnection = null;
});
connection.on('disconnected', function () {
global.cachedConnection = null;
});
connection.on('close', function () {
global.cachedConnection = null;
});
process.on('SIGINT', function () {
connection.close(function () {
process.exit(0);
});
});
} else {
global.cachedConnection = null;
}
}, (reason) => {
global.cachedConnection = null; //Retry connection during next call
return callback(errorResp(reason));
});
return global.connectionPromise;
} catch (error) {
console.error(error);
global.cachedConnection = null;
return callback(errorResp(error));
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment