DEV Community

Matt Chaffe
Matt Chaffe

Posted on

3 1

Feathersjs background hooks

Feathersjs is an open source REST and realtime API layer for modern applications.

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.

module.exports = function () {
return function runInBackground (context) {
const { app } = context
// Fire off async task
app.service('email').create({ email: 'info@mattchaffe.uk', message: 'Send In Background' })
// Continue to next hook before the above call is resolved
return context
}
}

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 thefeathers-hooks-common` comes in handy

{% gist https://gist.github.com/Mattchewone/0931d8903a4bcdde675851a2e5a6e173 %}

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.

{% gist https://gist.github.com/Mattchewone/4215286d23bf90fc8131f768253de229 %}

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.

{% gist https://gist.github.com/Mattchewone/297caaea9eb40c9d0a03318d3dcd88b0 %}

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more