You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 13:45:04