ajv-validator / ajv-merge-patch

$merge and $patch keywords for Ajv JSON-Schema validator to extend schemas
https://ajv.js.org
MIT License
46 stars 17 forks source link

Merge schemas with required keyword #36

Closed 5LICK closed 4 years ago

5LICK commented 4 years ago

Hi, If I try to merge schemas with "required" keyword, as result incorrect merge of "required" values.

Test schema

{
  "$merge": {
    "source": {
      "required": ["foo", "bar"],
      "properties": {
        "foo": { "type": "string" },
        "bar": { "type": "string" }
      }
    },
    "with": {
      "required": ["baz"],
      "properties": {
        "baz": { "type": "number" }
      }
    }
  }
}

Schema after compile

{
    "$merge": {
        "source": {
            "required": [
                "baz"
            ],
            "properties": {
                "foo": {
                    "type": "string"
                },
                "bar": {
                    "type": "string"
                },
                "baz": {
                    "type": "number"
                }
            }
        },
        "with": {
            "required": [
                "baz"
            ],
            "properties": {
                "baz": {
                    "type": "number"
                }
            }
        }
    }
}

Test validation

const validate = ajv.compile(schema)

validate({"foo": "asd", "bar": "asd", "baz": 123})
true
validate({"foo": "asd", "baz": 123})
true
validate({"baz": 123})
true
validate({"foo": "asd"})
false
5LICK commented 4 years ago

Ok, it seems it is global behavior of merge implementation. (close)

epoberezkin commented 4 years ago

Indeed - you can use $patch instead - it allows modifying arrays.