fixed some some mongdb stuff, and added hide objects

This commit is contained in:
Boki 2025-06-21 07:33:47 -04:00
parent 8edd78a341
commit a0e1593af9
6 changed files with 37 additions and 12 deletions

View file

@ -7,19 +7,38 @@ import type { Db } from 'mongodb';
* Provides global access to a single MongoDB connection
*/
let instance: MongoDBClient | null = null;
let initPromise: Promise<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();
if (instance) {
return instance;
}
if (initPromise) {
return initPromise;
}
if (!config) {
throw new Error('MongoDB client not initialized. Call connectMongoDB(config) first.');
}
initPromise = (async () => {
const client = new MongoDBClient(config);
await client.connect();
instance = client;
return client;
})();
try {
return await initPromise;
} catch (error) {
// Reset promise on error so next call can retry
initPromise = null;
throw error;
}
return instance;
}
/**
@ -59,4 +78,5 @@ export async function disconnectMongoDB(): Promise<void> {
await instance.disconnect();
instance = null;
}
initPromise = null;
}