Feathersjs background hooks

Matt Chaffe
2 min readMar 9, 2018

--

If you require hook(s) to run after you have responded to the client, for example with a process that is likely to take a few seconds to complete and the response of the hooks isn’t required by the actual service being called, then you can return the context from the hook and allow the function to be run.

background hook

Running a single hook is relatively straightforward as the above hook shows. But I required to run multiple hooks in sequence, with each one depending on the previous one.

Here is where combine from the feathers-hooks-common comes in handy

hook1

The above hook shows a rather simplistic hook that will look up all records with a name property, it will add them to the params object.

hook2

This second hook will filter out existing names so we are left with new names to create. Say we had a large amount of names to create or we had some hooks that ran on the names being created and we didn’t wish to wait for the create to finish before we responded to the client from the initial request.

combined hooks

We can combine the hooks and return the context immediately, the hooks will run “in the background”. The response will be sent to the client whilst the hooks are still being processed by the event loop.

--

--