Files
FlockPal/backend/src/db/client.ts
T
Corey Blais 3237cd7601
Deploy / deploy-prod (push) Skipped
Deploy / deploy-dev (push) Successful in 4m18s
Added behavior journal, adjusted layout, and added some colors
2026-10-05 15:20:00 -04:00

47 lines
1.2 KiB
TypeScript

import dotenv from 'dotenv';
import pg, { type QueryResult, type QueryResultRow } from 'pg';
dotenv.config();
type QueryParams = unknown[] | undefined;
export class DatabaseClient {
private readonly pool: pg.Pool;
constructor() {
const { Pool } = pg;
this.pool = new Pool({
host: process.env.POSTGRES_HOST ?? 'localhost',
port: Number(process.env.POSTGRES_PORT ?? 5432),
database: process.env.POSTGRES_DB ?? 'flockpal',
user: process.env.POSTGRES_USER ?? 'flockpal',
password: process.env.POSTGRES_PASSWORD ?? 'flockpal_dev_password',
});
}
query<T extends QueryResultRow>(text: string, params?: QueryParams): Promise<QueryResult<T>> {
return this.pool.query<T>(text, params);
}
async transaction<T>(operation: (client: pg.PoolClient) => Promise<T>): Promise<T> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
const result = await operation(client);
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
async close() {
await this.pool.end();
}
}
export const db = new DatabaseClient();