build fixes

This commit is contained in:
Alexander Harding
2026-07-31 20:56:22 -04:00
parent 749dbcfe55
commit 7144ac8fed
2 changed files with 37 additions and 21 deletions
+36 -17
View File
@@ -1,23 +1,42 @@
import { MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI!;
const options = {};
/**
* 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).
*/
let client: MongoClient;
let clientPromise: Promise<MongoClient>;
if (process.env.NODE_ENV === "development") {
const globalWithMongo = global as typeof globalThis & {
_mongoClientPromise?: Promise<MongoClient>;
};
if (!globalWithMongo._mongoClientPromise) {
client = new MongoClient(uri, options);
globalWithMongo._mongoClientPromise = client.connect();
}
clientPromise = globalWithMongo._mongoClientPromise;
} else {
client = new MongoClient(uri, options);
clientPromise = client.connect();
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;