如何从 handler/controller 文件访问 fastify 实例?

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

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

索引:

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'
    })
  }
}

谢谢!

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'
    })
  }
}

更新:
您可以使用 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'
    });
  }
};

fastify.decorateRequest('fastify', 禁食);现在会return一条警告信息:

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

以下是请求的 OnRequest 挂钩的更新用法:

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

如果需要回复,请将“onRequest”替换为“onReply”。 See Fastify docs on it here.

这是默认添加的

module.exports = { getRoot: (request, reply) {
// ACCESS FASTIFY NAMESPACE HERE
const fastify = request.server; 
/* The Fastify server instance, scoped to the current encapsulation context */
reply.code(204).send({
  type: 'warning',
  message: 'No content'
})}}

参考:https://www.fastify.io/docs/latest/Reference/Request/