ajv 验证失败,架构正确 "data should NOT have additional properties"

ajv validate fails with correct schema "data should NOT have additional properties"

我正在使用 ajv 来验证一些 JSON 数据,然后再将其写入数据库。我的请求数据基本上是这样的(作为示例):

文档:

"name": "John",
"id": "123-456-789"

这将传递给 ajv 验证器:

const validator: ajv.Ajv = this.getValidator();
validator.validate("Testschema.out", doc)

这就是 Testschema.out 的样子

{
    "id": "Testschema.out",
    "type": "object",
    "allOf": [{
            "$ref": "anotherId#/definitions/someDefinition"
        },
        {
            "$ref": "Testschema"
        }
    ]
}

Testschema 包含这个:

{
    "id": "Testschema",
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        }
    },
    "additionalProperties": false,
    "required": [
        "name"
    ]
}

虽然 someDefinition 持有这个:

{
    "id": "anotherId",
    "type": "object",
    "definitions": {
        "someDefinition": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                }
            }
        }
    }
}

但是,验证失败,我得到的错误是 "data should NOT have additional properties" 具体来说,"anotherId" 架构中的任何内容由于某种原因都无法通过验证。如果我在何处将 "id" 属性 添加到 Testschema,则验证将通过。

原来问题出在 allOf 关键字和 "Testschema." 上的 "additionalProperties": false 请参阅:https://spacetelescope.github.io/understanding-json-schema/reference/combining.html#allof

似乎新的 $merge 关键字就是这个问题的答案:https://github.com/epoberezkin/ajv-merge-patch