Skip to content

Commit ce50a0f

Browse files
committed
fix: lazy-init DB client to avoid build-time connection failure
1 parent bd994e9 commit ce50a0f

1 file changed

Lines changed: 21 additions & 6 deletions

File tree

src/server/db/index.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,25 @@ import postgres from "postgres";
22
import { drizzle } from "drizzle-orm/postgres-js";
33
import * as schema from "./schema";
44

5-
const queryClient = postgres(process.env.DATABASE_URL!, {
6-
max: 10,
7-
idle_timeout: 20,
8-
connect_timeout: 10,
9-
});
5+
let _db: ReturnType<typeof drizzle> | null = null;
6+
7+
export function getDb() {
8+
if (!_db) {
9+
const queryClient = postgres(process.env.DATABASE_URL!, {
10+
max: 10,
11+
idle_timeout: 20,
12+
connect_timeout: 10,
13+
});
14+
_db = drizzle(queryClient, { schema });
15+
}
16+
return _db;
17+
}
1018

11-
export const db = drizzle(queryClient, { schema });
19+
// Backward-compatible `db` getter
20+
export const db = new Proxy({} as ReturnType<typeof drizzle>, {
21+
get(_target, prop, receiver) {
22+
const real = getDb();
23+
const val = Reflect.get(real, prop, receiver);
24+
return typeof val === "function" ? val.bind(real) : val;
25+
},
26+
});

0 commit comments

Comments
 (0)