Skip to content

Commit 3fea7fe

Browse files
author
Toni Leigh Sharpe
authored
Update README with instructions for transact
Adds in a README section covering the transact option Resolves fastify#75
1 parent 9513db6 commit 3fea7fe

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

README.md

+27
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,33 @@ fastify.listen(3000, err => {
230230
})
231231
```
232232

233+
### Transact route option
234+
It's 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.
235+
236+
`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.
237+
238+
```js
239+
// transact set for the route pg client
240+
fastify.get('/user/:id', { pg: { transact: true } }, (req, reply) => {
241+
// transaction wrapped queries, NO error handling
242+
req.pg.query('SELECT username FROM users WHERE id=1')
243+
req.pg.query('SELECT username FROM users WHERE id=2')
244+
req.pg.query('SELECT username FROM users WHERE id=3')
245+
})
246+
247+
// transact set for a pg client at name
248+
fastify.get('/user/:id', { pg: { transact: 'foo' } }, (req, reply) => {
249+
// transaction wrapped queries, NO error handling
250+
req.pg.foo.query('SELECT username FROM users WHERE id=1')
251+
req.pg.foo.query('SELECT username FROM users WHERE id=2')
252+
req.pg.foo.query('SELECT username FROM users WHERE id=3')
253+
})
254+
```
255+
256+
Important: rolling back a transaction relies on the handler failing and being caught by an `onError` hook. This means that the transaction wrapped route handler mustn't catch any errors internally.
257+
258+
In the plugin this works by using the `preHandler` hook to open the transaction, then the `onError` and `onSend` hooks to commit or rollback and release the client back to the pool.
259+
233260
## TypeScript Usage
234261

235262
Install the compiler and typings for pg module:

0 commit comments

Comments
 (0)