Spaces:
Running
Running
| import pg from 'pg'; | |
| import { config } from '../config.js'; | |
| const { Pool } = pg; | |
| export const pool = new Pool({ | |
| host: config.database.host, | |
| port: config.database.port, | |
| database: config.database.database, | |
| user: config.database.user, | |
| password: config.database.password, | |
| max: 20, | |
| idleTimeoutMillis: 30000, | |
| connectionTimeoutMillis: 10000, | |
| }); | |
| export async function query<T extends pg.QueryResultRow = any>(text: string, params?: any[]): Promise<pg.QueryResult<T>> { | |
| return pool.query<T>(text, params); | |
| } | |
| export async function getClient(): Promise<pg.PoolClient> { | |
| return pool.connect(); | |
| } | |
| export async function transaction<T>(fn: (client: pg.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 (e) { | |
| await client.query('ROLLBACK'); | |
| throw e; | |
| } finally { | |
| client.release(); | |
| } | |
| } | |