disclosure-bureau/web/lib/retrieval/db.ts

34 lines
881 B
TypeScript
Raw Permalink Normal View History

/**
* Postgres connection pool shared across server-side retrieval calls.
*
* Reads DATABASE_URL (or SUPABASE_DB_URL). Direct pg client bypasses the
* Supabase REST/RLS layer so our service-role queries are first-class.
*/
import { Pool } from "pg";
const url = process.env.DATABASE_URL || process.env.SUPABASE_DB_URL;
let _pool: Pool | null = null;
export function getPool(): Pool {
if (_pool) return _pool;
if (!url) {
throw new Error("DATABASE_URL (or SUPABASE_DB_URL) is not set");
}
_pool = new Pool({
connectionString: url,
max: Number(process.env.PG_POOL_MAX || 5),
idleTimeoutMillis: 30_000,
});
return _pool;
}
export async function pgQuery<T = Record<string, unknown>>(
text: string,
params: unknown[] = [],
): Promise<T[]> {
const pool = getPool();
const res = await pool.query(text, params);
return res.rows as T[];
}