UNPKG

@sigiljs-community/mongo-plugin

Version:

Plugin for SigilJS framework that provides MongoDB interactions

92 lines (91 loc) 2.71 kB
class o { constructor(t, n, e) { this.client = t, this._dbName = n, this.log = e; } _database; /** * Tracks the current connection status. * @default ConnectionStatus.Disconnected * @private */ _connectionStatus = 1; /** * Gets the current connection status. */ get connectionStatus() { return this._connectionStatus; } /** * Gets the name of the configured database. */ get databaseName() { return this._dbName; } /** * Gets the current database instance, if connected. */ get db() { return this._database; } /** * Gets the current database instance, cast as non-undefined. * Use with caution; throws if not connected. */ get unsafeDB() { return this._database; } /** * Ensures that there is an active connection to the database. * @throws Error if not connected */ checkConnection() { if (this._connectionStatus !== 0) throw new Error("Not connected to database"); } /** * Disconnects from the MongoDB server. * If already disconnected, does nothing. * @returns promise that resolves to true if disconnection succeeded or was unnecessary, * or false if an error occurred during client.close() */ async disconnect() { return this._connectionStatus === 1 ? !0 : await this.client.close().catch(() => null) === null ? !1 : (this._connectionStatus = 1, this.log({ level: "info", message: `Connection to database ${this._dbName} closed`, json: { milestone: "disconnect", ok: !0 } }), !0); } /** * Connects (or reconnects) to the MongoDB server and selects the database. * If already connected, does nothing. * @returns promise that resolves to true if connection succeeded or was unnecessary, * or false if an error occurred during client.connect() */ async reconnect() { if (this._connectionStatus === 0) return !0; const t = performance.now(); if (!await this.client.connect().catch(() => null)) return !1; this._database = this.client.db(this._dbName); const e = performance.now() - t; return this._connectionStatus = 0, this.log({ level: "info", message: `Connection to database ${this._dbName} established in ${e}ms`, json: { milestone: "connect", ok: !0, time: e, db: this._dbName } }), !0; } /** * Retrieves a collection from the connected database. * @typeParam T shape of the documents in the collection * @param name name of the collection to access * @returns MongoDB Collection instance * @throws Error if not connected */ collection(t) { return this.checkConnection(), this.unsafeDB.collection(t); } } export { o as default };