handlerfastify

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!


Solution

  • routes/auth:

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

    handler/auth:

    module.exports = function (fastify) {
      getRoot: (request, reply) {
        fastify;
        reply.code(204).send({
          type: 'warning',
          message: 'No content'
        })
      }
    }