Skip to content

Commit

Permalink
fix(database): connection returning true even if error occured
Browse files Browse the repository at this point in the history
  • Loading branch information
polonel committed Oct 1, 2018
1 parent 55bfff8 commit 0156c4b
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 deletions src/database/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,32 +23,32 @@ var dbPassword = encodeURIComponent(nconf.get('mongo:password'));

var CONNECTION_URI = 'mongodb://' + nconf.get('mongo:username') + ':' + dbPassword + '@' + nconf.get('mongo:host') + ':' + nconf.get('mongo:port') + '/' + nconf.get('mongo:database');

mongoose.connection.on('error', function(e) {
winston.error('Oh no, something went wrong with DB! - ' + e.message);
});

mongoose.connection.on('connected', function() {
if (!process.env.FORK)
winston.info('Connected to MongoDB');
});

var options = { keepAlive: 1, connectTimeoutMS: 30000, useNewUrlParser: true };

module.exports.init = function(callback, connectionString, opts) {
if (connectionString) CONNECTION_URI = connectionString;
if (opts) options = opts;
if (!_.isUndefined(process.env.MONGOHQ_URL)) CONNECTION_URI = process.env.MONGOHQ_URL.trim();

mongoose.connection.once('error', function(e) {
winston.error('Oh no, something went wrong with DB! - ' + e.message);
db.connection = null;
return callback(e, null);
});

mongoose.connection.once('connected', function() {
if (!process.env.FORK)
winston.info('Connected to MongoDB');

db.connection = mongoose.connection;
return callback(null, db);
});

if (db.connection)
return callback(null, db);

mongoose.Promise = global.Promise;
mongoose.connect(CONNECTION_URI, options, function(e) {
if (e) return callback(e, null);
db.connection = mongoose.connection;

return callback(e, db);
});
mongoose.connect(CONNECTION_URI, options).catch(function(e) { return callback(e, null); });
};

module.exports.db = db;

0 comments on commit 0156c4b

Please sign in to comment.