Skip to content

Commit ae82f20

Browse files
committed
Added transaction helper
1 parent e39d415 commit ae82f20

File tree

2 files changed

+74
-1
lines changed

2 files changed

+74
-1
lines changed

index.js

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

6+
function transactionHelper (query, values) {
7+
return new Promise((resolve, reject) => {
8+
this.connect((err, client, done) => {
9+
if (err) reject(err)
10+
11+
const shouldAbort = (err) => {
12+
if (err) {
13+
client.query('ROLLBACK', (err) => {
14+
done()
15+
reject(err)
16+
})
17+
}
18+
return !!err
19+
}
20+
21+
client.query('BEGIN', (err) => {
22+
if (shouldAbort(err)) reject(err)
23+
client.query(query, values, (err, res) => {
24+
if (shouldAbort(err)) reject(err)
25+
26+
client.query('COMMIT', (err) => {
27+
done()
28+
if (err) {
29+
reject(err)
30+
}
31+
resolve(res)
32+
})
33+
})
34+
})
35+
})
36+
})
37+
}
38+
639
function fastifyPostgres (fastify, options, next) {
740
if (options.native) {
841
delete options.native
@@ -21,7 +54,8 @@ function fastifyPostgres (fastify, options, next) {
2154
connect: pool.connect.bind(pool),
2255
pool: pool,
2356
Client: pg.Client,
24-
query: pool.query.bind(pool)
57+
query: pool.query.bind(pool),
58+
transact: transactionHelper.bind(pool)
2559
}
2660

2761
if (name) {

test.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,3 +253,42 @@ test('fastify.pg.test should throw with duplicate connection names', t => {
253253
t.is(err.message, 'Connection name has already been registered: test')
254254
})
255255
})
256+
257+
test('fastify.pg.test use transact util', t => {
258+
t.plan(2)
259+
260+
const fastify = Fastify()
261+
262+
fastify.register(fastifyPostgres, {
263+
name: 'test',
264+
connectionString: 'postgres://postgres@localhost/postgres'
265+
})
266+
267+
fastify.ready(err => {
268+
t.error(err)
269+
fastify.pg.test
270+
.query('CREATE TABLE users(username VARCHAR (50) NOT NULL)')
271+
.then(result => {
272+
fastify.pg.test
273+
.transact('INSERT INTO users(username) VALUES($1)', ['brianc'])
274+
.then(result => {
275+
fastify.pg.test
276+
.query('SELECT * FROM users')
277+
.then(result => {
278+
t.ok(result.rows[0].one === 'brianc')
279+
}).catch(err => {
280+
t.fail(err)
281+
fastify.close()
282+
})
283+
})
284+
.catch(err => {
285+
t.fail(err)
286+
fastify.close()
287+
})
288+
})
289+
.catch(err => {
290+
t.fail(err)
291+
fastify.close()
292+
})
293+
})
294+
})

0 commit comments

Comments
 (0)