import * as mongoose from "mongoose" ; import * as winston from "winston" ; import Bluebird = require ( "bluebird" ) ; ( < any > mongoose ) . Promise = Bluebird ; export class Database { private dbURI : string ; constructor ( dbURI ) { this . dbURI = dbURI ; } public connect ( ) { const options = { autoIndex : true , poolSize : 500 , reconnectTries : Number . MAX_VALUE , reconnectInterval : 1000 } ; mongoose . connect ( this . dbURI , options ) . then ( ( ) => { this . hookIntoConnectionMonitorEvents ( ) ; this . setupShutdownHandlers ( ) ; } ) . catch ( ( err ) => { winston . error ( `Could not connect to Mongo with error: ${ err }` ) ; } ) ; } private hookIntoConnectionMonitorEvents ( ) { mongoose . connection . on ( "connected" , ( ) => { winston . info ( "Mongoose connected" ) ; } ) ; mongoose . connection . on ( "error" , ( err ) => { winston . info ( `Mongoose connection error: ${ err }` ) ; } ) ; mongoose . connection . on ( "disconnected" , ( ) => { winston . info ( "Mongoose disconnected" ) ; } ) ; } private setupShutdownHandlers ( ) { process . once ( "SIGUSR2" , ( ) => { mongoose . connection . close ( ( ) => { winston . info ( "Mongoose disconnected through nodemon restart" ) ; process . kill ( process . pid , "SIGUSR2" ) ; } ) ; } ) ; process . on ( "SIGINT" , ( ) => { mongoose . connection . close ( ( ) => { winston . info ( "Mongoose disconnected through app termination" ) ; process . exit ( 0 ) ; } ) ; } ) ; process . on ( "SIGTERM" , ( ) => { mongoose . connection . close ( ( ) => { winston . info ( "Mongoose disconnected through Heroku app shutdown" ) ; process . exit ( 0 ) ; } ) ; } ) ; } }