Trimming alternatives for anyOf/oneOf based on type#170
Trimming alternatives for anyOf/oneOf based on type#170srivastava-diya wants to merge 3 commits intohyperjump-io:mainfrom
Conversation
Add a newline at the end of the JSON file
Add missing newline at the end of anyOf.json
| const anyOfSchema = await getSchema(schemaLocation); | ||
| const alternativeSchema = await Schema.step(String(i), anyOfSchema); | ||
| const typeSchema = await Schema.step("type", alternativeSchema); | ||
| const type = /** @type {string | string[]} */ (Schema.value(typeSchema)); |
There was a problem hiding this comment.
This will only work in simple schemas. Consider an alternative schema that is just a $ref to another schema that provides defines type. You can use normalizedErrors instead to get the type information.
It occurs to me that we might have some duplication with the type error handler. Let's try to consider how to avoid that duplication.
| "anyOf": [ | ||
| { | ||
| "type": "string", | ||
| "maxLength": 2 | ||
| }, | ||
| { | ||
| "type": "string", | ||
| "maxLength": 4 | ||
| }, | ||
| { | ||
| "type": "number", | ||
| "minimum": 2 | ||
| } | ||
| ] |
There was a problem hiding this comment.
This is an interesting case because this could be collapsed into a single message: "Expected a string with no more than 4 characters". Let's change this test to something that can't be collapsed so the test doesn't break if we find a way to collapse these kinds of messages in the future.
Also, please open an issue with this case so we can discuss and think about how we might handle cases like this.
Description
This PR improves the error reporting for
anyOfandoneOfkeywords by filtering out irrelevant schema alternatives based on the instance's type. This results in significantly cleaner error messages.Fixes : #165
Changes
The error handlers now check the type keyword of each alternative. If an alternative expects a type different from the instance it is excluded from the error report.
If filtering results in
only onealternative, then anyOf / oneOf wrapper error is removed entirely.If no alternatives match the instance type (or if types aren't specified), the original behavior is preserved all alternatives are reported.