UNPKG

@notross/mongo-singleton

Version:

A lightweight, zero-fuss way to get a single shared MongoDB connection across your Node.js codebase.

45 lines 1.55 kB
import { Db, MongoClient } from 'mongodb'; import { ConnectionProps, SparseConnectionProps } from './types'; /** * MongoSingleton * * Manages a single, shared MongoDB connection for the application. * Subsequent calls to `.connect()` return the same connection. * * Like me, it's single and looking for a connection. 💔 */ export default class MongoSingleton { private databaseName; private uri; client: MongoClient | null; database: Db | null; status: string; error?: any; /** * @param connectionProps - Either a full ConnectionProps object, a SparseConnectionProps object, or a raw MongoDB URI string. * @param database - The name of the database to operate on. */ constructor(connectionProps: ConnectionProps | SparseConnectionProps | string, database: string); private initializeLogging; private initializeClient; private initializeDatabase; private getDb; /** * Establishes a connection to MongoDB if not already connected. * If already connected, returns the existing client and database. * * @returns Promise resolving to the connected MongoClient and Db. * @example * const { client, database } = await mongoClient.connect(); */ connect(): Promise<{ client: MongoClient; database: Db; }>; /** * Gracefully closes the MongoDB connection and resets internal state. * If no client exists, logs a warning instead. */ disconnect(): Promise<void>; } //# sourceMappingURL=client.d.ts.map