Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access fastify instance from a handler/controller file?

I need to access the fastify instance from a handler file. I don't remember at all how I should be doing that.

index:

fastify.register(require('./routes/auth'), {
  prefix: '/auth'
})

routes/auth:

module.exports = function(fastify, opts, next) {
  const authHandler = require('../handlers/auth')
  fastify.get('/', authHandler.getRoot)
  next()
}

handler/auth:

module.exports = {
  getRoot: (request, reply) {
    // ACCESS FASTIFY NAMESPACE HERE
    reply.code(204).send({
      type: 'warning',
      message: 'No content'
    })
  }
}

Thanks!

like image 596
HypeWolf Avatar asked Mar 06 '23 05:03

HypeWolf


1 Answers

fastify.decorateRequest('fastify', fastify); Will now return a warning message:

FastifyDeprecation: You are decorating Request/Reply with a reference type. This reference is shared amongst all requests. Use onRequest hook instead. Property: fastify

Here is the updated usage for the OnRequest hook for requests:

fastify.decorateRequest('fastify', null)    
fastify.addHook("onRequest", async (req) => {
        req.fastify = fastify;
}); 

Replace "onRequest" with "onReply" if needed for replies. See Fastify docs on it here.

like image 146
zenijos10 Avatar answered Apr 25 '23 02:04

zenijos10