Skip to content

Commit e2235ef

Browse files
committed
Add multiple queries in transaction
1 parent 4db4943 commit e2235ef

File tree

2 files changed

+11
-10
lines changed

2 files changed

+11
-10
lines changed

index.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
const fp = require('fastify-plugin')
44
var pg = require('pg')
55

6-
function transactionUtil (pool, query, values, cb) {
6+
function transactionUtil (pool, fn, cb) {
77
pool.connect((err, client, done) => {
88
if (err) return cb(err)
99

@@ -18,32 +18,33 @@ function transactionUtil (pool, query, values, cb) {
1818

1919
client.query('BEGIN', (err) => {
2020
if (shouldAbort(err)) return cb(err)
21-
client.query(query, values, (err, res) => {
22-
if (shouldAbort(err)) return cb(err)
2321

22+
fn(client).then(res => {
2423
client.query('COMMIT', (err) => {
2524
done()
2625
if (err) {
2726
return cb(err)
2827
}
2928
return cb(null, res)
3029
})
30+
}).catch(err => {
31+
if (shouldAbort(err)) return cb(err)
3132
})
3233
})
3334
})
3435
}
3536

36-
function transact (query, values, cb) {
37+
function transact (fn, cb) {
3738
if (!cb) {
3839
return new Promise((resolve, reject) => {
39-
transactionUtil(this, query, values, function (err, res) {
40+
transactionUtil(this, fn, function (err, res) {
4041
if (err) { return reject(err) }
4142
return resolve(res)
4243
})
4344
})
4445
}
4546

46-
return transactionUtil(this, query, values, cb)
47+
return transactionUtil(this, fn, cb)
4748
}
4849

4950
function fastifyPostgres (fastify, options, next) {

test.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -268,9 +268,9 @@ test('fastify.pg.test use transact util with promise', t => {
268268
t.error(err)
269269
fastify.pg.test
270270
.query('CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL)')
271-
.then(result => {
271+
.then(() => {
272272
fastify.pg.test
273-
.transact('INSERT INTO users(username) VALUES($1) RETURNING id', ['brianc'])
273+
.transact(client => { client.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['brianc']) })
274274
.then(result => {
275275
t.ok(result.rows[0].id === 1)
276276
fastify.pg.test
@@ -308,9 +308,9 @@ test('fastify.pg.test use transact util with callback', t => {
308308
t.error(err)
309309
fastify.pg.test
310310
.query('CREATE TABLE users2(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL)')
311-
.then(function () {
311+
.then(() => {
312312
fastify.pg.test
313-
.transact('INSERT INTO users2(username) VALUES($1) RETURNING id', ['brianc'], function (err, res) {
313+
.transact(client => { client.query('INSERT INTO users2(username) VALUES($1) RETURNING id', ['brianc']) }, function (err, res) {
314314
if (err) {
315315
t.fail(err)
316316
fastify.close()

0 commit comments

Comments
 (0)