fixing up db's and data-service

This commit is contained in:
Boki 2025-06-19 23:45:38 -04:00
parent aca98fdce4
commit 71f9b0a886
9 changed files with 211 additions and 19 deletions

View file

@ -0,0 +1,62 @@
import { MongoDBClient } from './client';
import type { MongoDBClientConfig } from './types';
import type { Db } from 'mongodb';
/**
* Singleton MongoDB client instance
* Provides global access to a single MongoDB connection
*/
let instance: MongoDBClient | null = null;
/**
* Initialize the singleton MongoDB client
*/
export async function connectMongoDB(config?: MongoDBClientConfig): Promise<MongoDBClient> {
if (!instance) {
if (!config) {
throw new Error('MongoDB client not initialized. Call connectMongoDB(config) first.');
}
instance = new MongoDBClient(config);
await instance.connect();
}
return instance;
}
/**
* Get the singleton MongoDB client instance
* @throws Error if not initialized
*/
export function getMongoDBClient(): MongoDBClient {
if (!instance) {
throw new Error('MongoDB client not initialized. Call connectMongoDB(config) first.');
}
return instance;
}
/**
* Get the MongoDB database instance
* @throws Error if not initialized
*/
export function getDatabase(): Db {
if (!instance) {
throw new Error('MongoDB client not initialized. Call connectMongoDB(config) first.');
}
return instance.getDatabase();
}
/**
* Check if the MongoDB client is initialized
*/
export function isInitialized(): boolean {
return instance !== null && instance.connected;
}
/**
* Disconnect and reset the singleton instance
*/
export async function disconnectMongoDB(): Promise<void> {
if (instance) {
await instance.disconnect();
instance = null;
}
}