不使用数组如何在JSON Schema中实现对象递归引用建模
问题原因
JSON Schema 规范本身完全支持对象类型的递归定义,不存在仅允许数组场景递归的限制,你遇到的栈溢出报错是 Fastify 内置的序列化工具 fast-json-stringify 早期版本对递归对象引用的处理逻辑不完善导致的。
修复方案
1. 优化Schema定义
将分类结构统一定义为递归类型,写法更规范也更容易被序列化工具识别:
{ "$schema": "http://json-schema.org/draft-07/schema", "$id": "https://www.example.com/schemas/food.json", "type": "object", "required": ["name", "category"], "properties": { "name": { "type": "string" }, "category": { "$ref": "#/$defs/category" } }, "$defs": { "category": { "type": ["object", "null"], "required": ["name"], "properties": { "name": { "type": "string" }, "parent": { "$ref": "#/$defs/category" } } } } }
2. 适配Fastify配置
- 优先升级 Fastify 及相关依赖到最新稳定版,
fast-json-stringify从v3.x版本开始已经原生支持对象递归引用场景,升级后绝大多数情况可以直接解决栈溢出问题。 - 如果受业务限制无法升级版本,可以给对应路由添加序列化配置开启循环引用支持:
fastify.get('/foods/:id', { schema: { response: { 200: 上面定义的FoodSchema } }, serializerOpts: { circular: true } }, async (request, reply) => { // 业务逻辑 })
- 如果是校验阶段报错,可以给 Fastify 的 AJV 校验器配置添加
strict: false关闭严格模式即可。
内容的提问来源于stack exchange,提问作者Check12
相关产品推荐
相关产品推荐

