钩子函数
通过使用钩子,可以直接在 Fastify 的生命周期内进行交互,共有三种不同的Hook(按执行顺序):
'onRequest'
'preHandler'
'onResponse'
'onClose'
Example:
fastify.addHook('onRequest', (req, res, next) => {
// some code
next()
})
fastify.addHook('preHandler', (request, reply, next) => {
// some code
next()
})
fastify.addHook('onResponse', (res, next) => {
// some code
next()
})
参数 | 描述 |
---|---|
req | Node.js Http 请求对象 |
res | Node.js Http 响应对象 |
request | Fastify Request 接口 |
reply | Fastify Reply 接口 |
next | 继续下一个 生命周期 任务 |
很容易理解每个钩子执行的位置,如果你需要视觉反馈来理解可以查看生命周期页面。
如果在执行钩子函数时遇到错误,只需将其传递给 next()
,并且 Fastify 将自动关闭请求并向用户发送相应的错误代码。
fastify.addHook('onRequest', (req, res, next) => {
next(new Error('some error'))
})
如果你希望传递一个自定义状态码,可以使用reply.code()
:
fastify.addHook('preHandler', (request, reply, next) => {
reply.code(500)
next(new Error('some error'))
})
这个错误将会被 Reply 处理。
注意,在 preHandler
钩子中,request
和 reply
参数与onRequest
中的不同,onRequest
中的请求参数是未经处理的 Node http
模块的请求参数,而 request
和 reply
是经过 Fastify 处理过的。
onClose
'onClose'
是唯一不在生命周期中的钩子,当调用 fastify.close()
来停止服务器时,会触发此钩子,如果你有一些需要“关闭”的操作,则它很有用,例如:与数据库的连接。
只有这个钩子,函数的参数会改变,第一个是 Fastify 实例,第二个用来完成回调。
fastify.addHook('onClose', (instance, done) => {
// some code
done()
})
Scope
除了 'onClose'
之外,其他钩子都是可以封装的,这意味着可以通过 register
来封装钩子运行时的作用域。
beforeHandler
beforeHandler
并不是一个和 preHandler
一样的 fastify 生命周期钩子,它是一个访问特定路由时中执行的路由钩子函数。如果你需要在路由级别而不是生命周期级别(例如:preHandler
)处理认证,这将会变得很有用。它也可以是一个函数数组。
注意:beforeHandler
总是在 preHandler
之后执行.
fastify.addHook('preHandler', (request, reply, done) => {
// your code
done()
})
fastify.route({
method: 'GET',
url: '/',
schema: { ... },
beforeHandler: function (request, reply, done) {
// your code
done()
},
handler: function (request, reply) {
reply.send({ hello: 'world' })
}
})
fastify.route({
method: 'GET',
url: '/',
schema: { ... },
beforeHandler: [
function first (request, reply, done) {
// your code
done()
},
function second (request, reply, done) {
// your code
done()
}
],
handler: function (request, reply) {
reply.send({ hello: 'world' })
}
})