Skip to content

Commit

Permalink
Added transaction helper
Browse files Browse the repository at this point in the history
  • Loading branch information
cemremengu committed Sep 20, 2018
1 parent e39d415 commit fbf5a5a
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
36 changes: 35 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,39 @@
const fp = require('fastify-plugin')
var pg = require('pg')

function transactionHelper (query, values) {
return new Promise((resolve, reject) => {
this.connect((err, client, done) => {
if (err) reject(err)

const shouldAbort = (err) => {
if (err) {
client.query('ROLLBACK', (err) => {
done()
reject(err)
})
}
return !!err
}

client.query('BEGIN', (err) => {
if (shouldAbort(err)) reject(err)
client.query(query, values, (err, res) => {
if (shouldAbort(err)) reject(err)

client.query('COMMIT', (err) => {
done()
if (err) {
reject(err)
}
resolve(res)
})
})
})
})
})
}

function fastifyPostgres (fastify, options, next) {
if (options.native) {
delete options.native
Expand All @@ -21,7 +54,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: transactionHelper.bind(pool)
}

if (name) {
Expand Down
40 changes: 40 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,43 @@ test('fastify.pg.test should throw with duplicate connection names', t => {
t.is(err.message, 'Connection name has already been registered: test')
})
})

test('fastify.pg.test use transact util', t => {
t.plan(3)

const fastify = Fastify()

fastify.register(fastifyPostgres, {
name: 'test',
connectionString: 'postgres://postgres@localhost/postgres'
})

fastify.ready(err => {
t.error(err)
fastify.pg.test
.query('CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL)')
.then(result => {
fastify.pg.test
.transact('INSERT INTO users(username) VALUES($1) RETURNING id', ['brianc'])
.then(result => {
t.ok(result.rows[0].id === 1)
fastify.pg.test
.query('SELECT * FROM users')
.then(result => {
t.ok(result.rows[0].username === 'brianc')
}).catch(err => {
t.fail(err)
fastify.close()
})
})
.catch(err => {
t.fail(err)
fastify.close()
})
})
.catch(err => {
t.fail(err)
fastify.close()
})
})
})

0 comments on commit fbf5a5a

Please sign in to comment.