import { MongoClient } from "mongodb"; import { AppError } from "../errors"; import { defaultsDeep } from "lodash"; import { logger as defaultLogger } from "../utils/Logger"; export class MongoDB { private _connection: any = undefined; private _isSettingUpConnection: any = false; private config: any; private logger: any = null; private tracer: any = null; /** * [constructor description] * @param {[type]} opts [description] * @param {[type]} _logger [description] * @param {[type]} _tracer = undefined [description] */ constructor(opts?, _logger = defaultLogger, _tracer = undefined) { let my = this; my.logger = _logger; my.tracer = _tracer; my.config = defaultsDeep({}, opts, { url: "mongodb://user:pass@localhost:30000", options: { poolSize: 100, socketTimeoutMS: 60000 } }); my.setConnection() .then(() => { my.logger.info("MongDB is ready!"); }) .catch(err => { my.logger.error(err); throw err; //fail hard in case of network failure }); } /** * [getConnection description] * @return {any} [description] */ public getConnection(): any { var self = this; if (!self.isConnected()) { return Promise.resolve(self.setConnection()); } return Promise.resolve(self._connection); } /** * [closeConnection description] */ public closeConnection() { if (!this.isConnected()) return; this._connection.close(); this._connection = undefined; this._isSettingUpConnection = false; } /** * [isConnected description] * @return {boolean} [description] */ private isConnected(): boolean { return !!this._connection; } /** * [setConnection description] * @return {any} [description] */ private setConnection(): any { var self = this; if (!!self._isSettingUpConnection) { return Promise.resolve(self._isSettingUpConnection); } return (self._isSettingUpConnection = new Promise(function( resolve, reject ) { MongoClient.connect( self.config.url, self.config.options, (err, conn) => { if (err) { self.logger.info("Mongo error found!"); self._isSettingUpConnection = false; //reset trigger self.logger.error(err.stack); // the real internal error return reject( new AppError( "Unable to reach DB", "DBConnectionError", 503 ) ); } self._connection = conn; resolve(self._connection); } ); })); } }