Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export async function tx(db, query) {
- const client = await db.connect()
- try {
- await client.query('BEGIN')
- try {
- await query(client)
- client.query('COMMIT')
- } catch(e) {
- client.query('ROLLBACK')
- }
- } finally {
- client.release()
- }
- }
- // Alternatively using an arrow function:
- const tx = (db, query) => {
- const client = await db.connect()
- try {
- await client.query('BEGIN')
- try {
- await query(client)
- client.query('COMMIT')
- } catch(e) {
- client.query('ROLLBACK')
- }
- } finally {
- client.release()
- }
- }
- // Usage:
- const pool = new Pool();
- await tx(pool, async (txClient) => {
- // Do what you need to do within your transaction here..
- await txClient.query(`UPDATE users SET password = 'foo' WHERE username = 'bar'`);
- await txClient.query(`UPDATE users SET password = 'foo' WHERE username = 'baz'`);
- });
Add Comment
Please, Sign In to add comment