Skip to content

Commit

Permalink
Add multiple queries in transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
cemremengu committed Sep 21, 2018
1 parent 4db4943 commit 80761b5
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
13 changes: 7 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const fp = require('fastify-plugin')
var pg = require('pg')

function transactionUtil (pool, query, values, cb) {
function transactionUtil (pool, fn, cb) {
pool.connect((err, client, done) => {
if (err) return cb(err)

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

client.query('BEGIN', (err) => {
if (shouldAbort(err)) return cb(err)
client.query(query, values, (err, res) => {
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)
})
})
})
}

function transact (query, values, cb) {
function transact (fn, cb) {
if (!cb) {
return new Promise((resolve, reject) => {
transactionUtil(this, query, values, function (err, res) {
transactionUtil(this, fn, function (err, res) {
if (err) { return reject(err) }
return resolve(res)
})
})
}

return transactionUtil(this, query, values, cb)
return transactionUtil(this, fn, cb)
}

function fastifyPostgres (fastify, options, next) {
Expand Down
8 changes: 4 additions & 4 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,9 @@ test('fastify.pg.test use transact util with promise', t => {
t.error(err)
fastify.pg.test
.query('CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL)')
.then(result => {
.then(() => {
fastify.pg.test
.transact('INSERT INTO users(username) VALUES($1) RETURNING id', ['brianc'])
.transact(client => { return client.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['brianc']) })
.then(result => {
t.ok(result.rows[0].id === 1)
fastify.pg.test
Expand Down Expand Up @@ -308,9 +308,9 @@ test('fastify.pg.test use transact util with callback', t => {
t.error(err)
fastify.pg.test
.query('CREATE TABLE users2(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL)')
.then(function () {
.then(() => {
fastify.pg.test
.transact('INSERT INTO users2(username) VALUES($1) RETURNING id', ['brianc'], function (err, res) {
.transact(client => { return client.query('INSERT INTO users2(username) VALUES($1) RETURNING id', ['brianc']) }, function (err, res) {
if (err) {
t.fail(err)
fastify.close()
Expand Down

0 comments on commit 80761b5

Please sign in to comment.