Skip to content

Helper functions #2107

@jwalton

Description

@jwalton

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions