Post hooks¶
A post hook is a TypeScript function of yours which runs after an API, with its result in g.res.output. It can reshape the answer, add to it, replace it, send something somewhere, or refuse to answer at all. It lives at the same levels as a pre hook : instance, database, table, API, custom, system and third party API, with optional groups.
Order¶
Post hooks run from the narrowest level to the widest : the hooks of the API, then of the table, then of the database, then of the instance, each list top to bottom. The last one to run sees what every other one did.
The code¶
| The hook | Effect |
|---|---|
| returns nothing | The next post hook runs, then the answer is sent. |
changes g.res.output |
The answer is what is in g.res.output at the end. |
| returns a value | That value becomes the answer and the remaining post hooks do not run. |
| throws | The request answers with the error, whatever the API did. The database change of the API is not rolled back by that. |
- Hooks run in the sandbox (or on the native process with
runOnNativeProcess), within the sandbox timeout of the call. - No hook runs when the answer comes from the cache. Calls from your own code skip hooks unless
skipHookRunning: false.
Reshape the answer¶
Do something after a write¶
- For a notification to WebSocket clients, nothing to write : subscribers of the table are notified after every successful call. Emit a custom WebSocket event with
g.sys.system.emitEventWSwhen the notification needs another shape. - For an event after an API hit without code, attach the event to the API on the Events page (automatic trigger).
Streams¶
On get all by stream and query by stream the rows are already on their way when the post hooks run : g.res.output only holds the last chunk, and a value returned or thrown can not change what was sent. Reshape a stream in a custom API around g.sys.db.getAllByStream instead.
Good to know¶
- WebSocket notifications and automatic events run after the post hooks, on the final answer. A post hook which throws still lets the notification go out ; a pre hook which throws does not.
- Post hooks have versions and a Test button on the API testing page, like pre hooks, and deploy with Git.