Created
October 23, 2018 18:26
-
-
Save abuzarhamza/922a48612bb2e4d56c90533d02927f42 to your computer and use it in GitHub Desktop.
dbConnection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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