42 lines
1.0 KiB
TypeScript
42 lines
1.0 KiB
TypeScript
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
import { Pool } from 'pg';
|
|
import { authSchema } from './schema';
|
|
|
|
type AuthDrizzleDb = ReturnType<typeof createDb>;
|
|
|
|
declare global {
|
|
// eslint-disable-next-line no-var
|
|
var __fiscalAuthPgPool: Pool | undefined;
|
|
// eslint-disable-next-line no-var
|
|
var __fiscalAuthDrizzleDb: AuthDrizzleDb | undefined;
|
|
}
|
|
|
|
function getConnectionString() {
|
|
const connectionString = process.env.DATABASE_URL?.trim();
|
|
if (!connectionString) {
|
|
throw new Error('DATABASE_URL is required for PostgreSQL.');
|
|
}
|
|
|
|
return connectionString;
|
|
}
|
|
|
|
export function getPool() {
|
|
if (!globalThis.__fiscalAuthPgPool) {
|
|
globalThis.__fiscalAuthPgPool = new Pool({
|
|
connectionString: getConnectionString()
|
|
});
|
|
}
|
|
|
|
return globalThis.__fiscalAuthPgPool;
|
|
}
|
|
|
|
function createDb() {
|
|
return drizzle(getPool(), { schema: authSchema });
|
|
}
|
|
|
|
export const db = globalThis.__fiscalAuthDrizzleDb ?? createDb();
|
|
|
|
if (!globalThis.__fiscalAuthDrizzleDb) {
|
|
globalThis.__fiscalAuthDrizzleDb = db;
|
|
}
|