钩子
钩子
¥Hooks
钩子使用 fastify.addHook
方法注册,允许你监听应用或请求/响应生命周期中的特定事件。你必须在事件触发之前注册一个钩子,否则事件将丢失。
¥Hooks are registered with the fastify.addHook
method and allow you to listen
to specific events in the application or request/response lifecycle. You have to
register a hook before the event is triggered, otherwise, the event is lost.
通过使用钩子,你可以直接与 Fastify 的生命周期进行交互。有请求/响应钩子和应用钩子:
¥By using hooks you can interact directly with the lifecycle of Fastify. There are Request/Reply hooks and application hooks:
ℹ️ 注意:使用
async
/await
或返回Promise
时,done
回调不可用。如果在这种情况下调用done
回调,可能会发生意外行为,例如重复调用处理程序。¥ℹ️ Note: The
done
callback is not available when usingasync
/await
or returning aPromise
. If you do invoke adone
callback in this situation unexpected behavior may occur, e.g. duplicate invocation of handlers.
Request/Reply 钩子
¥Request/Reply Hooks
¥Request and Reply are the core Fastify objects.
done
是继续 lifecycle 的函数。
¥done
is the function to continue with the lifecycle.
通过查看 生命周期页面,很容易理解每个钩子在哪里执行。
¥It is easy to understand where each hook is executed by looking at the lifecycle page.
Hooks 受到 Fastify 封装的影响,因此可以应用于选定的路由。有关更多信息,请参阅 Scopes 部分。
¥Hooks are affected by Fastify's encapsulation, and can thus be applied to selected routes. See the Scopes section for more information.
你可以在请求/响应中使用八种不同的钩子(按执行顺序):
¥There are eight different hooks that you can use in Request/Reply (in order of execution):
onRequest
fastify.addHook('onRequest', (request, reply, done) => {
// Some code
done()
})
或 async/await
:
¥Or async/await
:
fastify.addHook('onRequest', async (request, reply) => {
// Some code
await asyncMethod()
})