import { CreateConnectionString, IConnectionOptions } from "./Utils"; import { Observable, BehaviorSubject } from "rxjs"; // MongoDB import { MongoClient, Db, MongoError } from "mongodb"; export class MongoConnection { protected _OnConnectedSubject: BehaviorSubject = new BehaviorSubject(null); protected _db: Db = null; protected _mongoClient: MongoClient; constructor(private options: IConnectionOptions) { } OnConnect(): Observable { return this._OnConnectedSubject.asObservable(); } protected async _connected() { } connect(options?: IConnectionOptions): Promise { if(!options) { options = this.options; } let connectionString = CreateConnectionString(options); return MongoClient.connect(connectionString, { autoReconnect: true, }).then(async (client: MongoClient) => { this._db = client.db(options.Database); this._mongoClient = client; await this._connected(); this._OnConnectedSubject.next(true); return client; }); } // Closes the mongo connection close(forceClose: boolean = false): Promise { if(!this._db) { throw Error("Not connected."); } return this._mongoClient.close(forceClose); } };