Skip to content

feat: support oneOf - #267

Open
belfordzjeeves wants to merge 1 commit into
masterfrom
fix/201-support-oneof
Open

belfordzjeeves wants to merge 1 commit into
masterfrom
fix/201-support-oneof

Conversation

@belfordzjeeves

Copy link
Copy Markdown
Contributor

Fixes #201

Root cause (two parts)

  1. validateItem in src/index.ts only dispatched on schema.type; a schema carrying oneOf (and no type) silently validated as true at its own level.
  2. Worse, the traverse(schema, ...) walk in validator() visited each branch at paths like $.oneOf[0], and schemaPathToRegularPath drops the oneOf[0] token, so every branch subschema was validated against the parent's data — producing false errors (e.g. the {type: "number"} branch checked against "potato").

Fix

  • src/base-validators/oneOf.ts (new): OneOfValidationError following the existing error-class pattern; added to the ValidationError union in src/index.ts.
  • validateItem now handles oneOf: it counts branches where validateItem(branch, data) === true. Exactly one match returns true; otherwise a OneOfValidationError is collected with reason expected data to match exactly one schema in oneOf, but N matched. Recursion through validateItem makes nested oneOf (in a branch, in an object property) work.
  • The validator() traverse callback skips subschemas sitting under a oneOf keyword (matched by /(^|\.)oneOf\[\d+\]/), since validateItem handles them recursively at the oneOf schema. A data property literally named oneOf yields paths like $.properties.oneOf (no bracket index) and is deliberately not skipped — covered by a precision test.
  • Out of scope: allOf/anyOf/not untouched.

Verification

  • Issue repro before fix: both cases returned ValidationErrors; after fix both return true.
  • Full suite: 7 suites, 45 tests, all green. Coverage: 98.39% statements / 94.5% branches / 100% functions / 98.3% lines — above the jest.config.js thresholds (94.28 / 87.77 / 100 / 93.99). New oneOf.ts is 100% covered.
  • npx tsc --noEmit clean.
  • New regression tests in src/index.test.ts: the issue's two cases verbatim, both-branches-match, neither-matches, oneOf in an object property (valid + invalid), oneOf nested in a oneOf branch, and the property-literally-named-oneOf precision test.

validateItem now counts branches matching the data; exactly one match
validates, otherwise a OneOfValidationError is reported. The validator's
traverse walk skips subschemas beneath oneOf keywords (they are handled
recursively at the oneOf schema) so branches are no longer checked
against the parent schema's data.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

support oneOf

1 participant