Last active
March 12, 2019 01:36
-
-
Save officer-rosmarino/647bd76231b8b2b695380d42a4bc1999 to your computer and use it in GitHub Desktop.
How to properly handle a transaction with node-pg-pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const { Pool } = require('pg') | |
// create a pool instance. | |
// Refer to https://node-postgres.com/api/pool for more info on how to config pool | |
var pool = new Pool({ | |
"host": "YOUR_HOST", | |
"port": YOURPORT, | |
"database": "DBNAME", | |
"user": "USERNAME", | |
"password": "PASSWORD", | |
"max": MAX_POOL_SIZE | |
}); | |
function foo() { | |
return pool.connect() | |
.then(client => client.query('begin [your desired isolation level]') | |
.then(() => bar(client)) | |
.then(() => client.query('commit')) | |
.catch(err => { | |
return client.query('rollback') | |
.catch(() => { }) | |
.then(() => { | |
client.release(); | |
return Promise.reject(err); | |
}) | |
} | |
)) | |
.catch(err => Promise.reject(err)); | |
} | |
function bar(client) { | |
return client.query('YOUR QUERY') | |
.then(() => Promise.resolve('resolve bar')) | |
.catch(() => Promise.reject('reject bar')) | |
} | |
foo() | |
.then((v) => { | |
console.log(v) | |
}) | |
.catch((e) => { | |
console.log(e) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment