@@ -23,9 +23,8 @@ export interface Form {
2323}
2424
2525// --- Persistence ---
26- if ( ! process . env . MONGODB_URI ) {
27- throw new Error ( 'Invalid/Missing environment variable: "MONGODB_URI"' ) ;
28- }
26+ // --- Persistence ---
27+ // NOTE: We check this lazily or let it fail at runtime in functions to allow build-time execution without env vars.
2928
3029const uri = process . env . MONGODB_URI ;
3130const dbName = process . env . MONGODB_DB_NAME || 'postpipe_core' ;
@@ -34,25 +33,34 @@ const options = {};
3433let client ;
3534let clientPromise : Promise < MongoClient > ;
3635
37- if ( process . env . NODE_ENV === 'development' ) {
38- // In development mode, use a global variable so that the value
39- // is preserved across module reloads caused by HMR (Hot Module Replacement).
40- // @ts -ignore
41- if ( ! global . _mongoClientPromise ) {
42- client = new MongoClient ( uri , options ) ;
36+ function getClientPromise ( ) : Promise < MongoClient > {
37+ if ( clientPromise ) return clientPromise ;
38+
39+ if ( ! uri ) {
40+ throw new Error ( 'Invalid/Missing environment variable: "MONGODB_URI"' ) ;
41+ }
42+
43+ if ( process . env . NODE_ENV === 'development' ) {
44+ // In development mode, use a global variable so that the value
45+ // is preserved across module reloads caused by HMR.
4346 // @ts -ignore
44- global . _mongoClientPromise = client . connect ( ) ;
47+ if ( ! global . _mongoClientPromise ) {
48+ client = new MongoClient ( uri , options ) ;
49+ // @ts -ignore
50+ global . _mongoClientPromise = client . connect ( ) ;
51+ }
52+ // @ts -ignore
53+ clientPromise = global . _mongoClientPromise ;
54+ } else {
55+ // In production mode, it's best to not use a global variable.
56+ client = new MongoClient ( uri , options ) ;
57+ clientPromise = client . connect ( ) ;
4558 }
46- // @ts -ignore
47- clientPromise = global . _mongoClientPromise ;
48- } else {
49- // In production mode, it's best to not use a global variable.
50- client = new MongoClient ( uri , options ) ;
51- clientPromise = client . connect ( ) ;
59+ return clientPromise ;
5260}
5361
5462async function getDB ( ) {
55- const c = await clientPromise ;
63+ const c = await getClientPromise ( ) ;
5664 return c . db ( dbName ) ;
5765}
5866
0 commit comments