29 lines
817 B
TypeScript
29 lines
817 B
TypeScript
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
|
import * as schema from './schema';
|
|
import '@/lib/env-config';
|
|
|
|
let _db: NodePgDatabase<typeof schema> | null = null;
|
|
|
|
function getDb() {
|
|
if (!_db) {
|
|
const DATABASE_URL = process.env.POSTGRES_URL;
|
|
if (!DATABASE_URL) {
|
|
throw new Error('POSTGRES_URL environment variable is required');
|
|
}
|
|
_db = drizzle(DATABASE_URL, { schema });
|
|
}
|
|
return _db;
|
|
}
|
|
|
|
export const db = new Proxy({} as NodePgDatabase<typeof schema>, {
|
|
get(target, prop) {
|
|
const database = getDb();
|
|
const value = database[prop as keyof typeof database];
|
|
return typeof value === 'function' ? value.bind(database) : value;
|
|
},
|
|
});
|
|
|
|
// Re-export schema types for convenience
|
|
export * from './schema';
|