@notross/mongo-singleton
Version:
A lightweight, zero-fuss way to get a single shared MongoDB connection across your Node.js codebase.
57 lines • 1.92 kB
TypeScript
import * as mongodb from 'mongodb';
import { ConnectAndGetDb, GetCollection, GetDatabase, InitClient, InitClientProps, SetConfig } 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 declare class MongoSingleton {
private config;
private databaseName;
private uri;
client: mongodb.MongoClient | null;
database: mongodb.Db | null;
status: string;
error?: any;
init: InitClient;
collection: GetCollection;
connectedDb: ConnectAndGetDb;
db: GetDatabase;
configure: SetConfig;
/**
* @param connection - 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(props?: InitClientProps);
private setup;
private setConfig;
private initializeLogging;
private initializeClient;
private initializeDatabase;
_getDb(): mongodb.Db;
/**
* 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: mongodb.MongoClient;
database: mongodb.Db;
}>;
/**
* Gracefully closes the MongoDB connection and resets internal state.
* If no client exists, logs a warning instead.
*/
disconnect(): Promise<void>;
getDb(): Promise<mongodb.Db>;
getCollection(name: string): mongodb.Collection<mongodb.Document>;
}
//# sourceMappingURL=mongo-singleton.d.ts.map