51 lines
1.4 KiB
TypeScript
51 lines
1.4 KiB
TypeScript
import { Pool, type PoolClient, type QueryResultRow } from "pg";
|
|
|
|
import { config } from "./config";
|
|
|
|
function connectionString(): string {
|
|
if (process.env.DATABASE_URL) return process.env.DATABASE_URL;
|
|
const host = process.env.DB_HOST;
|
|
if (host) {
|
|
const user = encodeURIComponent(process.env.DB_USER ?? "");
|
|
const password = encodeURIComponent(process.env.DB_PASSWORD ?? "");
|
|
const name = process.env.DB_NAME ?? "courier";
|
|
const port = process.env.DB_PORT ?? "5432";
|
|
return `postgresql://${user}:${password}@${host}:${port}/${name}`;
|
|
}
|
|
return config.databaseUrl;
|
|
}
|
|
|
|
const globalForPg = globalThis as unknown as { courierPool?: Pool };
|
|
|
|
export const pool =
|
|
globalForPg.courierPool ??
|
|
new Pool({ connectionString: connectionString(), max: 10 });
|
|
|
|
if (process.env.NODE_ENV !== "production") {
|
|
globalForPg.courierPool = pool;
|
|
}
|
|
|
|
export async function query<T extends QueryResultRow = QueryResultRow>(
|
|
text: string,
|
|
params: unknown[] = [],
|
|
) {
|
|
return pool.query<T>(text, params as never[]);
|
|
}
|
|
|
|
export async function transaction<T>(
|
|
fn: (client: PoolClient) => Promise<T>,
|
|
): Promise<T> {
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query("begin");
|
|
const result = await fn(client);
|
|
await client.query("commit");
|
|
return result;
|
|
} catch (error) {
|
|
await client.query("rollback");
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|