-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Open
Labels
Description
Hey, I use these two helper functions in pretty much every project I use node-postgres in. I was just wondering if you'd be open to a PR to add these to the project proper?
export async function withClient(pool: Pool, fn: (client: PoolClient) => Promise<void>) {
const client = await pool.connect();
try {
await fn(client);
} finally {
client.release();
}
}
export async function withTransaction(pool: Pool, fn: (client: PoolClient) => Promise<void>) {
await withClient(async client => {
try {
await client.query('BEGIN');
await fn(client);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
}
});
}The basic idea here is I can do:
await withTransaction(pool, async client => {
client.query(...);
});
and then there's no chance of me messing up and forgetting the ROLLBACK or forgetting to release the client from the pool; it all gets handled for me. If you're interested, I'll do up a PR and write some docs.