const { MongoClient } = require('mongodb'); const { config } = require('./config'); function createDbProvider({ settings = config, MongoClientClass = MongoClient } = {}) { let client = null; let pending = null; async function getDb() { if (!settings.mongoUri) throw new Error('MONGO_URI must be configured.'); if (!pending) { let candidate; pending = Promise.resolve().then(async () => { candidate = new MongoClientClass(settings.mongoUri); client = candidate; await candidate.connect(); return candidate.db(settings.mongoDb); }).catch(async () => { pending = null; client = null; if (candidate) await Promise.resolve().then(() => candidate.close()).catch(() => {}); throw new Error('Database connection failed. Check the server configuration.'); }); } return pending; } async function closeDb() { if (pending) await pending.catch(() => {}); const previous = client; client = null; pending = null; if (previous) await previous.close(); } return { getDb, closeDb }; } module.exports = { ...createDbProvider(), createDbProvider };