14 lines
661 B
TypeScript
14 lines
661 B
TypeScript
import { Pool, type PoolClient } from "pg";
|
|
|
|
const globalDb = globalThis as unknown as { promptPool?: Pool };
|
|
export function db() {
|
|
if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is required");
|
|
return globalDb.promptPool ??= new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
|
|
}
|
|
export async function transaction<T>(run: (client: PoolClient) => Promise<T>): Promise<T> {
|
|
const client = await db().connect();
|
|
try { await client.query("BEGIN"); const result = await run(client); await client.query("COMMIT"); return result; }
|
|
catch (error) { await client.query("ROLLBACK"); throw error; }
|
|
finally { client.release(); }
|
|
}
|