| import { MongoClient } from 'mongodb'; | |
| import { getConfig } from './config.js'; | |
| let clientPromise = null; | |
| let didLogConnect = false; | |
| function redactMongoUrl(url) { | |
| try { | |
| const parsed = new URL(String(url || '')); | |
| const protocol = parsed.protocol || 'mongodb:'; | |
| const host = parsed.host || ''; | |
| const dbPath = parsed.pathname || ''; | |
| const hasAuth = Boolean(parsed.username || parsed.password); | |
| const auth = hasAuth ? '<redacted>@' : ''; | |
| return `${protocol}//${auth}${host}${dbPath}`; | |
| } catch { | |
| return '<invalid-mongo-url>'; | |
| } | |
| } | |
| export async function getMongoClient() { | |
| if (!clientPromise) { | |
| const { mongoUrl, mongoDbName } = getConfig(); | |
| if (!didLogConnect) { | |
| console.log(`[mongo] connecting to ${redactMongoUrl(mongoUrl)} (db: ${mongoDbName})`); | |
| didLogConnect = true; | |
| } | |
| const client = new MongoClient(mongoUrl, { | |
| maxPoolSize: 10, | |
| }); | |
| clientPromise = client.connect().catch((error) => { | |
| clientPromise = null; | |
| throw error; | |
| }); | |
| } | |
| return clientPromise; | |
| } | |
| export const getMongo = getMongoClient; | |
| export async function getMongoDb() { | |
| const client = await getMongoClient(); | |
| const { mongoDbName } = getConfig(); | |
| return client.db(mongoDbName); | |
| } | |