else condition seems mandatory when using if/then along with required
🐛 Bug Report
I might be misunderstanding how if/then/else works (as explained here for example https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#ifthenelse) but it looks to me like else condition is mandatory when if/then is used.
To Reproduce
Steps to reproduce the behavior:
const fastJson = require('fast-json-stringify')
const stringify = fastJson({
type: 'object',
properties: {
isCoOwnership: {
type: 'boolean',
},
unitTotal: {
type: 'number',
},
},
required: ['isCoOwnership'],
if: {
properties: {
isCoOwnership: {
const: true,
},
},
},
then: {
required: ['unitTotal'],
}
})
console.log(stringify({ isCoOwnership: true, unitTotal: 12 })) // => { isCoOwnership: true, unitTotal: 12 }
console.log(stringify({ isCoOwnership: false })) // => {}
Expected behavior
The result should be { isCoOwnership: false } since the validation passes.
I was able to find a workaround, adding this else condition:
else: {
required: []
}
or
else: {
additionalProperties: true
}
Your Environment
- node version: 12.14.1
- fast-json-stringify version: 1.16.3
- os: MacOS
You found a nice bug! Would you like to send a PR to fix this?
For reference, the spec does not require the presence of else when then is present -- https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.section.9.2.2.1
Shouldn't the schema be returned as it is in case there is no else condition present and the if condition is also not met ? Or we can just add a blank else condition in case no else condition is present ?
Ajv Documentation states
If the data is invalid against the sub-schema in if keyword, then the validation result is equal to the result of data validation against the sub-schema in else keyword (if else is absent, the validation succeeds).
This also means that in case of no else "validation succeeds" or schema is returned as it is.
Shouldn't the schema be returned as it is in case there is no else condition present and the if condition is also not met ?
We don't return any schemas: if the condition is not met, nothing happens to the output JSON
Or we can just add a blank else condition in case no else condition is present ?
This could be a side-effect fix, that is not the case
Ajv works as expected: https://runkit.com/eomm/ajv
when the if condition is not met, the else is not executed (because there is not an else)
Fixed