Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ This plugin will add the `pg` namespace in your Fastify instance, with the follo
connect: the function to get a connection from the pool
pool: the pool instance
Client: a client constructor for a single query
query: an utility to perform a query without a transaction
query: a utility to perform a query _without_ a transaction
transact: a utility to perform a query _with_ a transaction
```

Example:
Expand Down Expand Up @@ -95,6 +96,30 @@ fastify.listen(3000, err => {
console.log(`server listening on ${fastify.server.address().port}`)
})
```

Use of `pg.transact`
```js
const fastify = require('fastify')

fastify.register(require('fastify-postgres'), {
connectionString: 'postgres://postgres@localhost/postgres'
})

fastify.post('/user/:username', (req, reply) => {
fastify.pg.transact(
'INSERT INTO users(username) VALUES($1) RETURNING id', [req.params.username],
function onResult (err, result) {
reply.send(err || result)
}
)
})

fastify.listen(3000, err => {
if (err) throw err
console.log(`server listening on ${fastify.server.address().port}`)
})
```

As you can see there is no need to close the client, since is done internally. Promises and async await are supported as well.

### Native option
Expand Down
46 changes: 45 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,49 @@
const fp = require('fastify-plugin')
var pg = require('pg')

function transactionUtil (pool, query, values, 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)
client.query(query, values, (err, res) => {
if (shouldAbort(err)) return cb(err)

client.query('COMMIT', (err) => {
done()
if (err) {
return cb(err)
}
return cb(null, res)
})
})
})
})
}

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

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

function fastifyPostgres (fastify, options, next) {
if (options.native) {
delete options.native
Expand All @@ -21,7 +64,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) {
Expand Down
72 changes: 72 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,75 @@ 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 with promise', 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()
})
})
})

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

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 users2(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL)')
.then(function () {
fastify.pg.test
.transact('INSERT INTO users2(username) VALUES($1) RETURNING id', ['brianc'], function (err, res) {
if (err) {
t.fail(err)
fastify.close()
} else {
t.ok(res.rows[0].id === 1)
}
})
})
.catch(err => {
t.fail(err)
fastify.close()
})
})
})