import {CONNECTION_STATUS, IConnection} from "@sugoi/orm";
import {Db, MongoClient} from "mongodb";
import {IMongoConnectionConfig} from "../interfaces/mongo-connection-config.interface";
export class MongoConnection implements IConnection, IMongoConnectionConfig {
protocol: string = `mongodb://`;
status: CONNECTION_STATUS;
public newParser: boolean = false;
connect(): Promise<boolean> {
const connectionConfig = {
authSource: this.authDB || this.db
if (this.user && this.password) {
connectionConfig['auth'] = {
if (this.shouldUseNewParser()) {
connectionConfig['useNewUrlParser'] = true;
return MongoClient.connect(this.getConnectionString(), connectionConfig)
.then((client: MongoClient) => {
client.on("error", () => this.disconnect());
this.connectionClient = {
dbInstance: client.db(this.db),
isConnected(): Promise<boolean> {
return Promise.resolve(this.status === CONNECTION_STATUS.CONNECTED);
public shouldUseNewParser(): boolean {
if (!this.connectionClient)
return Promise.resolve(false);
return this.connectionClient.client.close(true)
.then((disconnectObject) => {
this.status = CONNECTION_STATUS.DISCONNECTED
public getConnectionString() {
let connString = this.protocol;
if (this.user && this.password) {
connString += `${this.user}:${this.password}@`;
connString += `${this.hostName}:${this.port}`;