Fastify中如何对request.body进行条件Schema验证?
Fastify 条件请求体验证实现方案
你的需求完全可以实现,问题出在if关键字的schema写法上。AJV的严格模式要求所有schema片段必须明确指定type,你之前的if块缺少type: "object",导致触发严格模式报错;同时,未明确约束的schema可能让AJV的条件判断逻辑异常,出现误判。
以下是修正后的代码:
fastify.post("/user", { schema: { description: "Create a user", body: { type: "object", required: ["country"], properties: { state: { type: "string" }, country: { type: "string", enum: ["US", "GB"], }, }, // 完善if块:明确类型为object,同时指定country的约束 if: { type: "object", properties: { country: { const: "US" } }, // 确保country字段存在且值为US时才触发then逻辑 required: ["country"] }, then: { required: ["state"] } }, response: { //... }, }, }, function (request, reply) { // do something });
关键修正点:
- 在
if块中添加type: "object",符合AJV严格模式的schema规范,避免报错 - 给
if块加上required: ["country"],确保只有当country字段存在且值为"US"时,才会触发then中的必填校验 - 这样配置后,当
country为"US"时,state会被强制要求填写;当country为"GB"时,state为可选字段
内容的提问来源于stack exchange,提问作者keogh
相关产品推荐
相关产品推荐

