import Mongoose = require ( 'mongoose' ) ; import * as config from 'config' ; import { logger } from '../../middleware/common/logging' ; Mongoose . Promise = global . Promise ; class MongooseAccess { static mongooseInstance : any ; static mongooseConnection : Mongoose . Connection ; constructor ( ) { MongooseAccess . connect ( ) ; } static connect ( ) { if ( this . mongooseInstance ) { return this . mongooseInstance ; } let connectionString = config . get ( 'mongo.urlDocker' ) . toString ( ) ; this . mongooseConnection = Mongoose . connection ; this . mongooseConnection . once ( 'open' , ( ) => { logger . info ( 'Connect to an mongodb is opened.' ) ; } ) ; this . mongooseInstance = Mongoose . connect ( connectionString ) ; this . mongooseConnection . on ( 'connected' , ( ) => { logger . info ( 'Mongoose default connection open to ' + connectionString ) ; } ) ; this . mongooseConnection . on ( 'error' , ( msg ) => { logger . info ( 'Mongoose default connection message:' , msg ) ; } ) ; this . mongooseConnection . on ( 'disconnected' , ( ) => { setTimeout ( function ( ) { this . mongooseInstance = Mongoose . connect ( connectionString ) ; } , 10000 ) ; logger . info ( 'Mongoose default connection disconnected.' ) ; } ) ; this . mongooseConnection . on ( 'reconnected' , ( ) => { logger . info ( 'Mongoose default connection is reconnected.' ) ; } ) ; process . on ( 'SIGINT' , ( ) => { this . mongooseConnection . close ( ( ) => { logger . info ( 'Mongoose default connection disconnected through app termination.' ) ; process . exit ( 0 ) ; } ) ; } ) ; return this . mongooseInstance ; } } MongooseAccess . connect ( ) ; export { MongooseAccess } ;