You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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.
0 commit comments