Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. 'use strict';
  2.  
  3. const fastify = require('fastify')();
  4.  
  5. const promiseTimeout = ms =>
  6. new Promise(resolve => {
  7. setTimeout(resolve, ms);
  8. });
  9.  
  10. // This issue occurs with both callback and promise based `onSend` hooks
  11. fastify.addHook('onSend', (request, reply, payload, done) => {
  12. setTimeout(() => {
  13. done(null, payload);
  14. }, 50);
  15. });
  16. // fastify.addHook('onSend', async (request, reply, payload) => {
  17. // await promiseTimeout(50);
  18. // return payload;
  19. // });
  20.  
  21. fastify.route({
  22. method: 'GET',
  23. path: '/',
  24.  
  25. // With this hook, the handler is still called
  26. preHandler: async function(request, reply) {
  27. console.log('GET / -> preHandler()');
  28. reply.redirect('/login');
  29. },
  30.  
  31. // With this hook, the handler is not called (as expected)
  32. // preHandler: function(request, reply, next) {
  33. // console.log('GET / -> preHandler()');
  34. // reply.redirect('/login');
  35. // },
  36.  
  37. handler: function(request, reply) {
  38. console.log('GET / -> handler() !! This should never be shown !!');
  39. reply.send({ hello: 'world' });
  40. }
  41. });
  42.  
  43. fastify.route({
  44. method: 'GET',
  45. path: '/login',
  46. handler: function(request, reply) {
  47. console.log('GET /login -> handler()');
  48. reply.send('Please log in\n');
  49. }
  50. });
  51.  
  52. fastify.listen(3000, err => {
  53. if (err) throw err;
  54. const { port } = fastify.server.address();
  55.  
  56. console.log(`server listening on port ${port}`);
  57. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement