生命周期
生命周期
¥Lifecycle
此模式显示了 Fastify 的内部生命周期。
¥This schema shows the internal lifecycle of Fastify.
每个部分的右侧分支显示生命周期的下一阶段。左侧分支显示如果父级抛出错误,则生成的相应错误代码。Fastify 自动处理所有错误。
¥The right branch of each section shows the next phase of the lifecycle. The left branch shows the corresponding error code generated if the parent throws an error. All errors are automatically handled by Fastify.
Incoming Request
│
└─▶ Routing
│
└─▶ Instance Logger
│
4**/5** ◀─┴─▶ onRequest Hook
│
4**/5** ◀─┴─▶ preParsing Hook
│
4**/5** ◀─┴─▶ Parsing
│
4**/5** ◀─┴─▶ preValidation Hook
│
400 ◀─┴─▶ Validation
│
4**/5** ◀─┴─▶ preHandler Hook
│
4**/5** ◀─┴─▶ User Handler
│
└─▶ Reply
│
4**/5** ◀─┴─▶ preSerialization Hook
│
└─▶ onSend Hook
│
4**/5** ◀─┴─▶ Outgoing Response
│
└─▶ onResponse Hook
在 User Handler
之前或期间,可以调用 reply.hijack()
来:
¥Before or during the User Handler
, reply.hijack()
can be called to:
-
防止 Fastify 运行后续钩子和用户处理程序
¥Prevent Fastify from running subsequent hooks and the user handler
-
防止 Fastify 自动发送响应
¥Prevent Fastify from sending the response automatically
如果 reply.raw
用于发送响应,onResponse
钩子仍将被执行。
¥If reply.raw
is used to send a response, onResponse
hooks will still
be executed.
Reply 生命周期
¥Reply Lifecycle
当用户处理请求时,结果可能是:
¥When the user handles the request, the result may be:
-
在异步处理程序中:它返回一个有效载荷或抛出一个
Error
¥In an async handler: it returns a payload or throws an
Error
-
在同步处理程序中:它发送一个有效载荷或一个
Error
实例¥In a sync handler: it sends a payload or an
Error
instance
如果回复被劫持,则跳过所有后续步骤。否则,提交时,数据流如下:
¥If the reply was hijacked, all subsequent steps are skipped. Otherwise, when submitted, the data flow is as follows:
★ schema validation Error
│
└─▶ schemaErrorFormatter
│
reply sent ◀── JSON ─┴─ Error instance
│
│ ★ throw an Error
★ send or return │ │
│ │ │
│ ▼ │
reply sent ◀── JSON ─┴─ Error instance ──▶ setErrorHandler ◀─────┘
│
reply sent ◀── JSON ─┴─ Error instance ──▶ onError Hook
│
└─▶ reply sent
reply sent
表示 JSON 有效负载将通过以下之一进行序列化:
¥reply sent
means the JSON payload will be serialized by one of the following:
-
如果设置了 回复序列化器
¥The reply serializer if set
-
如果为 HTTP 状态代码设置了 JSON 模式,则触发 串行器编译器
¥The serializer compiler if a JSON schema is set for the HTTP status code
-
默认
JSON.stringify
函数¥The default
JSON.stringify
function