Fastify使用anyOf进行响应序列化异常问题求助
问题原因
Fastify默认启用removeAdditional: true的AJV配置,会依据匹配到的JSON Schema过滤未声明的属性。你的data字段通过anyOf定义了三种返回结构,但前两个schema默认允许额外属性(additionalProperties: true),导致返回tempToken结构时,第一个schema也能通过验证(该结构是合法对象,未违反第一个schema的任何约束)。Fastify会使用第一个schema进行序列化,过滤掉不在其properties中的tempToken和multipleChoice字段,最终返回空对象。
解决方法
给anyOf中的每个schema添加additionalProperties: false,确保每个schema仅匹配自身声明的字段结构;同时可添加required字段增强约束,避免误匹配。
修改后的核心schema示例
data: { anyOf: [ { type: "object", additionalProperties: false, required: ["token", "user"], properties: { token: { type: "string" }, user: { type: "object", additionalProperties: false, required: ["id", "phoneNumber"], properties: { id: { type: "number" }, phoneNumber: { type: "string" }, }, }, }, }, { type: "object", additionalProperties: false, required: ["tempToken", "multipleChoice"], properties: { tempToken: { type: "string" }, multipleChoice: { type: "object", additionalProperties: false, required: ["usernames", "locationAddresses"], properties: { usernames: { type: "array", items: { type: "string" } }, locationAddresses: { type: "array", items: { type: "string" }, }, }, }, }, }, { type: "object", additionalProperties: false, required: ["token", "user"], properties: { token: { type: "string" }, user: { type: "object", additionalProperties: false, required: ["id", "username"], properties: { id: { type: "number" }, username: { type: "string" }, }, }, }, }, ], }
补充说明
additionalProperties: false:禁止schema未声明的额外字段,确保每个anyOf项仅匹配自身结构。required:明确指定每个结构的必填字段,进一步避免跨schema的误匹配。- 若需要更严格的排他匹配,可将
anyOf替换为oneOf,结合上述配置效果更佳。
内容的提问来源于stack exchange,提问作者Javohir Mirzo Fazliddinov
相关产品推荐
相关产品推荐

