Skip to content

Instantly share code, notes, and snippets.

@ericmacfa ericmacfa/index.js
Last active Jul 5, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.