UNPKG

@kurai-io/mongo

Version:
65 lines (64 loc) 2.1 kB
import { Db, MongoClient } from 'mongodb'; export declare enum ConnectionStatus { /** The controller is currently connected to the database */ Connected = 0, /** The controller is currently disconnected from the database */ Disconnected = 1 } /** * Controller for managing MongoDB connections and operations. */ export default class MongoController { readonly mongoClient: MongoClient; private readonly dbName; private _database?; /** * Tracks the current connection status. * @default ConnectionStatus.Disconnected * @private */ private _connectionStatus; constructor(mongoClient: MongoClient, dbName: string); /** * Gets the current connection status. */ get connectionStatus(): ConnectionStatus; /** * Gets the name of the configured database. */ get databaseName(): string | null; /** * Gets the current database instance, if connected. */ get db(): Db | undefined; /** * Gets the current database instance, cast as non-undefined. * Use with caution; throws if not connected. */ get unsafeDB(): Db; /** * Ensures that there is an active connection to the database. * @throws Error if not connected */ checkConnection(): void; /** * 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() */ disconnect(): Promise<boolean>; /** * Connects to the MongoDB server and selects the database. * If already connected, does nothing. */ connect(): Promise<this>; /** * 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 extends object = any>(name: string): import('mongodb').Collection<T>; }