node-postgres transactions with callbacks or async/await? node-postgres transactions with callbacks or async/await? postgresql postgresql

node-postgres transactions with callbacks or async/await?


The creator of node-postgres (brianc) graciously provided an excellent response to my original question on GitHub. The short answer is that it is not a bad idea to perform transactions with async/await.

See his full response here: https://github.com/brianc/node-postgres/issues/1252#issuecomment-293899088


In addition to Rob Johansen's post I would like to share my TypeScript solution:

import { PoolClient } from "pg"import { pool } from "../database"const tx = async (callback: (client: PoolClient) => void) => {  const client = await pool.connect();  try {    await client.query('BEGIN')    try {      await callback(client)      await client.query('COMMIT')    } catch (e) {      await client.query('ROLLBACK')    }  } finally {    client.release()  }}export { tx }

Usage:

let result;await tx(async client => {  const { rows } = await client.query<{ cnt: string }>('SELECT COUNT(*) AS cnt FROM users WHERE username = $1', [username]);  result = parseInt(rows[0].cnt) > 0;});