Repository URL to install this package:
|
Version:
3.1.0 ▾
|
/* eslint-disable global-require*/
// ***** Load config *****
const SUPPRESS_NO_CONFIG_WARNING = process.env.SUPPRESS_NO_CONFIG_WARNING;
process.env.SUPPRESS_NO_CONFIG_WARNING = 'y';
import config from 'config';
process.env.SUPPRESS_NO_CONFIG_WARNING = SUPPRESS_NO_CONFIG_WARNING;
// No config? no database...
if ( config.has( 'database' ) ) {
const mongoose = require( 'mongoose' );
mongoose.Promise = require( 'bluebird' );
const debugDb = config.has( 'database.debug' ) ? config.get( 'database.debug' ) : false;
mongoose.set( 'debug', debugDb );
const debugNamespace = 'touchto';
const 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
const connect = () => {
global.database_connect_attempts += 1;
const uri = config.get( 'database.connect' );
const options = config.has( 'database.options' ) ? config.get( 'database.options' ) : {};
mongoose.connect( uri, options );
};
// If there is an error we need to know about it
mongoose.connection.on( 'error', ( err ) => {
console.error( err.stack );
} );
// On mongoose disconnect, attempt to reconnect
mongoose.connection.on( 'disconnected', ( ) => {
if ( global.database_connect_attempts > 2 ) {
debug( 'Database connection trouble, waiting %j seconds to try again...' );
setTimeout( () => {
process.nextTick( connect );
}, 1000 * global.database_connect_attempts );
} else {
process.nextTick( connect );
}
} );
// On Connected, yeah!
mongoose.connection.on( 'connected', ( err ) => {
if ( err ) {
console.error( err );
} else {
debug( 'Database Connected' );
}
} );
// Attempt connection
connect();
}