Files
dndextended/src/lib/mongodb.ts
T
Alexander Harding 7144ac8fed build fixes
2026-07-31 20:56:22 -04:00

43 lines
1.3 KiB
TypeScript

import { MongoClient } from "mongodb";
/**
* Lazy MongoClient promise. We don't touch `process.env.MONGODB_URI` at module
* import time so `next build` / page-data collection doesn't crash when the env
* isn't populated (e.g. inside a Docker build with no runtime env).
*/
declare global {
var _mongoClientPromise: Promise<MongoClient> | undefined;
}
function createClientPromise(): Promise<MongoClient> {
const uri = process.env.MONGODB_URI;
if (!uri) {
throw new Error("MONGODB_URI is not set");
}
const client = new MongoClient(uri, {});
return client.connect();
}
function getClientPromise(): Promise<MongoClient> {
if (process.env.NODE_ENV === "development") {
if (!globalThis._mongoClientPromise) {
globalThis._mongoClientPromise = createClientPromise();
}
return globalThis._mongoClientPromise;
}
if (!globalThis._mongoClientPromise) {
globalThis._mongoClientPromise = createClientPromise();
}
return globalThis._mongoClientPromise;
}
const clientPromise: Promise<MongoClient> = {
then: (onFulfilled, onRejected) => getClientPromise().then(onFulfilled, onRejected),
catch: (onRejected) => getClientPromise().catch(onRejected),
finally: (onFinally) => getClientPromise().finally(onFinally),
[Symbol.toStringTag]: "Promise",
} as Promise<MongoClient>;
export default clientPromise;