Files
websitedev/proto/src/lib/mongodb.ts
T

71 lines
2.5 KiB
TypeScript
Executable File

import { MongoClient, Db } from 'mongodb'
import { dbLogger, getSafeErrorDetails } from './logger'
// WHY this file only exposes getDb/checkMongoConnection now: it used to also
// export getCollection(), used by src/app/api/contact/route.ts for a raw,
// Payload-external `contact_submissions` collection. MITHOME-94 moved that
// write to a proper Payload collection (ContactSubmissions) via the Local
// API — getDb() itself stays alive only for /api/health's connectivity check.
const options = {
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
}
let clientPromise: Promise<MongoClient> | undefined
function createClientPromise(): Promise<MongoClient> {
const uri = process.env.MONGODB_URI
if (!uri) {
throw new Error('Please add MONGODB_URI to your environment variables')
}
return new MongoClient(uri, options).connect()
}
export function getClientPromise(): Promise<MongoClient> {
// In development mode, use a global variable so that the client is not recreated between hot reloads.
// The connection is intentionally created lazily: `next build` must not require runtime secrets.
if (process.env.NODE_ENV === 'development') {
// @ts-expect-error - Global variable for development hot reload
if (!global._mongoClientPromise) {
// @ts-expect-error - Global variable for development hot reload
global._mongoClientPromise = createClientPromise().catch((error: Error) => {
// A rejected promise must not stay cached: a transient failure would
// otherwise break every subsequent request in this process.
// @ts-expect-error - Global variable for development hot reload
global._mongoClientPromise = undefined
throw error
})
}
// @ts-expect-error - Global variable for development hot reload
return global._mongoClientPromise
}
clientPromise ??= createClientPromise().catch((error: Error) => {
// See the development branch above: drop the cached rejection so the next
// call can retry the connection.
clientPromise = undefined
throw error
})
return clientPromise
}
export async function getDb(): Promise<Db> {
const client = await getClientPromise()
return client.db(process.env.MONGODB_DB || 'mozdit')
}
// Health check for MongoDB connection
export async function checkMongoConnection(): Promise<boolean> {
try {
const db = await getDb()
await db.admin().ping()
return true
} catch (error) {
dbLogger.error('MongoDB connection check failed', getSafeErrorDetails(error))
return false
}
}