Guest User

Untitled

a guest
Mar 4th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. export async function tx(db, query) {
  2. const client = await db.connect()
  3. try {
  4. await client.query('BEGIN')
  5. try {
  6. await query(client)
  7. client.query('COMMIT')
  8. } catch(e) {
  9. client.query('ROLLBACK')
  10. }
  11. } finally {
  12. client.release()
  13. }
  14. }
  15.  
  16. // Alternatively using an arrow function:
  17.  
  18. const tx = (db, query) => {
  19. const client = await db.connect()
  20. try {
  21. await client.query('BEGIN')
  22. try {
  23. await query(client)
  24. client.query('COMMIT')
  25. } catch(e) {
  26. client.query('ROLLBACK')
  27. }
  28. } finally {
  29. client.release()
  30. }
  31. }
  32.  
  33. // Usage:
  34. const pool = new Pool();
  35. await tx(pool, async (txClient) => {
  36. // Do what you need to do within your transaction here..
  37. await txClient.query(`UPDATE users SET password = 'foo' WHERE username = 'bar'`);
  38. await txClient.query(`UPDATE users SET password = 'foo' WHERE username = 'baz'`);
  39. });
Add Comment
Please, Sign In to add comment