如何从处理程序/控制器文件访问固定实例?

时间:2018-10-23 01:39:03

标签: handler fastify

我需要从处理程序文件访问fastify实例。我完全不记得应该怎么做。

索引:

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

路由/身份验证:

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

处理程序/身份验证:

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

谢谢!

2 个答案:

答案 0 :(得分:0)

路由/身份验证:

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

处理程序/身份验证:

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

答案 1 :(得分:0)

更新
您可以使用this关键字访问由function关键字定义的控制器中的fastify实例。箭头功能控制器不起作用。

您还可以根据请求或回复对象装饰Fastify实例:

index

fastify.decorateRequest('fastify', fastify);
// or
fastify.decorateReply('fastify', fastify);

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

然后在您的handler/auth

module.exports = {
  getRoot: (request, reply) {
    // ACCESS FASTIFY NAMESPACE HERE
    request.fastify
    // or
    reply.fastify

    reply.code(204).send({
      type: 'warning',
      message: 'No content'
    });
  }
};
相关问题