import pg from "pg"; const { Pool } = pg; /** * Postgres devuelve NUMERIC como string para no perder precisión, y bigint igual. * El frontend declara `number` en shared/types.ts, así que se convierten aquí, en * el único sitio que abre conexiones, y no en cada handler. */ pg.types.setTypeParser(1700, (v: string) => Number(v)); // numeric pg.types.setTypeParser(20, (v: string) => Number(v)); // int8 / bigint const connectionString = process.env.DATABASE_URL || "postgres://yola:yola_dev@127.0.0.1:5434/yola"; export const pool = new Pool({ connectionString, max: 10 }); /** Ejecuta `fn` dentro de una transacción; hace ROLLBACK ante cualquier excepción. */ export async function withTx(fn: (c: pg.PoolClient) => Promise): Promise { const client = await pool.connect(); try { await client.query("BEGIN"); const out = await fn(client); await client.query("COMMIT"); return out; } catch (e) { await client.query("ROLLBACK"); throw e; } finally { client.release(); } }