Repository URL to install this package:
|
Version:
3.1.0 ▾
|
'use strict';
var _config = require('config');
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable global-require*/
// ***** Load config *****
var SUPPRESS_NO_CONFIG_WARNING = process.env.SUPPRESS_NO_CONFIG_WARNING;
process.env.SUPPRESS_NO_CONFIG_WARNING = 'y';
process.env.SUPPRESS_NO_CONFIG_WARNING = SUPPRESS_NO_CONFIG_WARNING;
// No config? no database...
if (_config2.default.has('database')) {
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var debugDb = _config2.default.has('database.debug') ? _config2.default.get('database.debug') : false;
mongoose.set('debug', debugDb);
var debugNamespace = 'touchto';
var debug = require('debug')(debugNamespace + ':database');
// Store globally the attempts to connect to the database
global.database_connect_attempts = global.database_connect_attempts || 0;
// connection helper
var connect = function connect() {
global.database_connect_attempts += 1;
var uri = _config2.default.get('database.connect');
var options = _config2.default.has('database.options') ? _config2.default.get('database.options') : {};
mongoose.connect(uri, options);
};
// If there is an error we need to know about it
mongoose.connection.on('error', function (err) {
console.error(err.stack);
});
// On mongoose disconnect, attempt to reconnect
mongoose.connection.on('disconnected', function () {
if (global.database_connect_attempts > 2) {
debug('Database connection trouble, waiting %j seconds to try again...');
setTimeout(function () {
process.nextTick(connect);
}, 1000 * global.database_connect_attempts);
} else {
process.nextTick(connect);
}
});
// On Connected, yeah!
mongoose.connection.on('connected', function (err) {
if (err) {
console.error(err);
} else {
debug('Database Connected');
}
});
// Attempt connection
connect();
}