28 lines
871 B
TypeScript
28 lines
871 B
TypeScript
// Postgres connection pool. Created lazily on first use so the module can be
|
|
// imported during build/analysis without DATABASE_URL being present.
|
|
import pg from 'pg';
|
|
import { env } from '$env/dynamic/private';
|
|
|
|
let pool: pg.Pool | null = null;
|
|
|
|
function getPool(): pg.Pool {
|
|
if (pool) return pool;
|
|
const connectionString = env.DATABASE_URL;
|
|
if (!connectionString) {
|
|
// Fail loudly on first query rather than mysteriously later.
|
|
throw new Error(
|
|
'DATABASE_URL is not set. Copy .env.example to .env (or set it in docker-compose) and try again.'
|
|
);
|
|
}
|
|
pool = new pg.Pool({ connectionString });
|
|
return pool;
|
|
}
|
|
|
|
/** Small helper so call sites read as `query(sql, params)`. */
|
|
export function query<T extends pg.QueryResultRow = pg.QueryResultRow>(
|
|
text: string,
|
|
params?: unknown[]
|
|
): Promise<pg.QueryResult<T>> {
|
|
return getPool().query<T>(text, params);
|
|
}
|