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

使用fluent-json-schema校验Schema全属性,获取所有缺失必填项错误

问题

使用fluent-json-schema校验请求头时,仅返回第一个缺失的必填项错误,而非全部缺失项。

我的headersSchema定义:

const headersSchema = S.object()
  .prop('platform', S.string()).required()
  .prop('device-data', S.string()).required()
  .prop('device-id', S.string()).required()
  .prop('consumer-id', S.string()).required()
  .prop('version', S.string()).required()

当前收到的错误信息:

[
  {
    "instancePath": "",
    "schemaPath": "#/required",
    "keyword": "required",
    "params": {
      "missingProperty": "device-data"
    },
    "message": "must have required property 'device-data'"
  }
]

实际未提交device-data和device-id两个请求头,希望同时获取这两个属性的缺失提示。路由代码:

server.post(
  '/headers',
  {
    schema: {
      headers: headersSchema
    }
  },
  () => {}
)
解决方案

这是因为fluent-json-schema底层依赖的Ajv校验库默认只返回第一个校验错误。要返回所有缺失的必填项错误,需开启Ajv的allErrors选项。

全局配置(推荐)

在创建Fastify实例时,统一配置Ajv选项:

const fastify = require('fastify')({
  ajv: {
    customOptions: {
      allErrors: true
    }
  }
})

单独路由配置

如果仅需要针对当前路由生效,可在路由的schema中添加Ajv配置:

server.post(
  '/headers',
  {
    schema: {
      headers: headersSchema,
      ajv: {
        customOptions: {
          allErrors: true
        }
      }
    }
  },
  () => {}
)

开启allErrors后,再次请求会返回所有缺失的必填项错误,示例如下:

[
  {
    "instancePath": "",
    "schemaPath": "#/required",
    "keyword": "required",
    "params": { "missingProperty": "device-data" },
    "message": "must have required property 'device-data'"
  },
  {
    "instancePath": "",
    "schemaPath": "#/required",
    "keyword": "required",
    "params": { "missingProperty": "device-id" },
    "message": "must have required property 'device-id'"
  }
]

内容的提问来源于stack exchange,提问作者Anthony Luzquiños

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 05:48:16