Skip to content
Merged
Changes from 1 commit
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
15 changes: 9 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,14 @@ fastify.register(require('@fastify/postgres'), {

fastify.get('/user/:id', async (req, reply) => {
const client = await fastify.pg.connect()
const { rows } = await client.query(
'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
)
client.release()
return rows
try {
const { rows } = await client.query(
'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
)
return rows
} finally {
client.release()
}
})

fastify.listen(3000, err => {
Expand Down Expand Up @@ -233,7 +236,7 @@ fastify.listen(3000, err => {
```

### Transact route option
It is possible to automatically wrap a route handler in a transaction by using the `transact` option when registering a route with Fastify. Note that the option must be scoped within a `pg` options object to take effect.
It is possible to automatically wrap a route handler in a transaction by using the `transact` option when registering a route with Fastify. Note that the option must be scoped within a `pg` options object to take effect.

`query` commands can then be accessed at `request.pg` or `request.pg[name]` and `transact` can be set for either the root pg client with value `true` or for a pg client at a particular namespace with value `name`. Note that the namespace needs to be set when registering the plugin in order to be available on the request object.

Expand Down