Skip to content

Commit 7638230

Browse files
authored
Docs: use try/finally to always release the client (#130)
1 parent 7d443cd commit 7638230

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

README.md

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,16 @@ fastify.register(require('@fastify/postgres'), {
6464

6565
fastify.get('/user/:id', async (req, reply) => {
6666
const client = await fastify.pg.connect()
67-
const { rows } = await client.query(
68-
'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
69-
)
70-
client.release()
71-
return rows
67+
try {
68+
const { rows } = await client.query(
69+
'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
70+
)
71+
// Note: avoid doing expensive computation here, this will block releasing the client
72+
return rows
73+
} finally {
74+
// Release the client immediately after query resolves, or upon error
75+
client.release()
76+
}
7277
})
7378

7479
fastify.listen(3000, err => {
@@ -233,7 +238,7 @@ fastify.listen(3000, err => {
233238
```
234239

235240
### Transact route option
236-
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.
241+
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.
237242

238243
`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.
239244

0 commit comments

Comments
 (0)