-
-
Notifications
You must be signed in to change notification settings - Fork 36
Added transaction helper #24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 7 commits
fbf5a5a
e01991c
66eee07
d7d188a
4db4943
80761b5
2b674e3
3708205
dc6540a
f45b1a6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,50 @@ | |
| const fp = require('fastify-plugin') | ||
| var pg = require('pg') | ||
|
|
||
| function transactionUtil (pool, fn, cb) { | ||
| pool.connect((err, client, done) => { | ||
| if (err) return cb(err) | ||
|
|
||
| const shouldAbort = (err) => { | ||
| if (err) { | ||
| client.query('ROLLBACK', () => { | ||
| done() | ||
| }) | ||
| } | ||
| return !!err | ||
| } | ||
|
|
||
| client.query('BEGIN', (err) => { | ||
| if (shouldAbort(err)) return cb(err) | ||
|
|
||
| fn(client).then(res => { | ||
|
||
| client.query('COMMIT', (err) => { | ||
| done() | ||
| if (err) { | ||
| return cb(err) | ||
| } | ||
| return cb(null, res) | ||
| }) | ||
| }).catch(err => { | ||
| if (shouldAbort(err)) return cb(err) | ||
| }) | ||
| }) | ||
| }) | ||
| } | ||
cemremengu marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| function transact (fn, cb) { | ||
| if (!cb) { | ||
| return new Promise((resolve, reject) => { | ||
| transactionUtil(this, fn, function (err, res) { | ||
| if (err) { return reject(err) } | ||
| return resolve(res) | ||
| }) | ||
| }) | ||
| } | ||
|
|
||
| return transactionUtil(this, fn, cb) | ||
| } | ||
|
|
||
| function fastifyPostgres (fastify, options, next) { | ||
| if (options.native) { | ||
| delete options.native | ||
|
|
@@ -21,7 +65,8 @@ function fastifyPostgres (fastify, options, next) { | |
| connect: pool.connect.bind(pool), | ||
| pool: pool, | ||
| Client: pg.Client, | ||
| query: pool.query.bind(pool) | ||
| query: pool.query.bind(pool), | ||
| transact: transact.bind(pool) | ||
| } | ||
|
|
||
| if (name) { | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.