Skip to content

Instantly share code, notes, and snippets.

@ericmacfa
Last active July 5, 2019 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericmacfa/e5331a632464ec4530c7a42617b67f45 to your computer and use it in GitHub Desktop.
Save ericmacfa/e5331a632464ec4530c7a42617b67f45 to your computer and use it in GitHub Desktop.
Fastify 1733 -- Lifecycle is not interrupted when onSend executes asynchronously
'use strict';
const fastify = require('fastify')();
const promiseTimeout = ms =>
new Promise(resolve => {
setTimeout(resolve, ms);
});
// This issue occurs with both callback and promise based `onSend` hooks
fastify.addHook('onSend', (request, reply, payload, done) => {
setTimeout(() => {
done(null, payload);
}, 50);
});
// fastify.addHook('onSend', async (request, reply, payload) => {
// await promiseTimeout(50);
// return payload;
// });
fastify.route({
method: 'GET',
path: '/',
// With this hook, the handler is still called
preHandler: async function(request, reply) {
console.log('GET / -> preHandler()');
reply.redirect('/login');
},
// With this hook, the handler is not called (as expected)
// preHandler: function(request, reply, next) {
// console.log('GET / -> preHandler()');
// reply.redirect('/login');
// },
handler: function(request, reply) {
console.log('GET / -> handler() !! This should never be shown !!');
reply.send({ hello: 'world' });
}
});
fastify.route({
method: 'GET',
path: '/login',
handler: function(request, reply) {
console.log('GET /login -> handler()');
reply.send('Please log in\n');
}
});
fastify.listen(3000, err => {
if (err) throw err;
const { port } = fastify.server.address();
console.log(`server listening on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment