我需要从处理程序文件访问 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'
})
}
}
谢谢!
fastify.decorateRequest('fastify', fastify);现在将返回警告消息:
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”。 请参阅此处的 Fastify 文档。
更新:
您可以使用
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'
});
}
};
有一种更简单的方法来访问
FastifyInstance
,无需创建函数包装器(闭包)或 fastify 装饰器:
fastify.get('/', function handler (req, _) { req.server; })
在上面的代码中,
req.server
指向FastifyInstance
。
与上述实例的唯一区别是它的范围仅限于当前路由上下文,如引用的文档中所述。
路线/授权:
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'
})
}
}
您可以从
request.server
访问 Fastify 实例,另请参阅:https://fastify.dev/docs/latest/Reference/Request/
所以在你的例子中:
getRoot: (request, reply) {
// Fastify instance
console.log(request.server)
}
自 PR 以来已添加此内容:https://github.com/fastify/fastify/pull/3102