import * as mongoose from 'mongoose' ; import { EventEmitter } from 'events' ; import { Mongoose } from 'mongoose' ; const db = mongoose ; const getMongoURL = ( options ) => { let url = options . servers . reduce ( ( prev , cur ) => `${ prev }${ cur },` , 'mongodb://' ) ; const queries = [ ] ; if ( options . replicaSet ) queries . push ( `replicaSet=${ options . replicaSet }` ) ; if ( options . authenticationDb ) queries . push ( `authSource=${ options . authenticationDb }` ) ; let query = queries . join ( '&' ) ; if ( query ) query = '?' + query ; url = `${ url . substr ( 0 , url . length - 1 ) }/${ options . db }` ; return url + query ; } ; let mediatorInstance ; export const connect = ( options , mediator ) => { db . connect ( getMongoURL ( options ) , { useNewUrlParser : true , poolSize : 3 , config : { autoIndex : [ 'developpement' , 'stage' , 'preprod' ] . indexOf ( process . env . NODE_ENV ) > - 1 } } ) . catch ( err => console . log ( '[ERROR]: ' , err ) ) ; db . connection . setMaxListeners ( 20 ) ; mediatorInstance = mediator ; db . connection . once ( 'connected' , ( ) => { if ( options . verbose ) { console . log ( `[INFO]: Mongoose default connection is open to ${ getMongoURL ( options ) }` ) ; } mediator . emit ( 'db.ready' , db ) ; } ) ; db . connection . once ( 'error' , ( err ) => { if ( options . verbose ) { console . log ( '[ERROR]: Mongoose default connection has occured ' + err + ' error' ) ; } mediator . emit ( 'db.error' , err ) ; } ) ; db . connection . once ( 'disconnected' , ( ) => { if ( options . verbose ) { console . log ( '[INFO]: Mongoose default connection is disconnected' ) ; } db . connection . removeAllListeners ( ) ; } ) ; process . once ( 'SIGINT' , ( ) => { db . connection . close ( ( ) => { if ( options . verbose ) { console . log ( '[ERROR]: Mongoose default connection is disconnected due to application termination' ) ; } process . exit ( 0 ) ; } ) ; } ) ; } ; export const disconnect = ( ) : Promise < void > => { mediatorInstance . removeAllListeners ( ) ; return db . disconnect ( ) ; } ;