Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | 5x 5x 5x 5x 5x | 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);
}
);
}));
}
}
|