Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: combine oneOf and anyOf handlers #440

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 3 additions & 25 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1192,11 +1192,10 @@ function nested (laterCode, name, key, location, subKey, isArray) {
code += `json += ${funcName}(obj${accessor})`
break
case undefined:
funcName = 'serializer.asNull.bind(serializer)'
if ('anyOf' in schema) {
if (schema.anyOf || schema.oneOf) {
// beware: dereferenceOfRefs has side effects and changes schema.anyOf
const anyOfLocations = dereferenceOfRefs(location, 'anyOf')
anyOfLocations.forEach((location, index) => {
const locations = dereferenceOfRefs(location, schema.anyOf ? 'anyOf' : 'oneOf')
locations.forEach((location, index) => {
const nestedResult = nested(laterCode, name, key, location, subKey !== '' ? subKey : 'i' + index, isArray)
// We need a test serializer as the String serializer will not work with
// date/time ajv validations
Expand All @@ -1221,27 +1220,6 @@ function nested (laterCode, name, key, location, subKey, isArray) {
`
laterCode = nestedResult.laterCode
})
code += `
else json+= null
`
} else if ('oneOf' in schema) {
// beware: dereferenceOfRefs has side effects and changes schema.oneOf
const oneOfLocations = dereferenceOfRefs(location, 'oneOf')
oneOfLocations.forEach((location, index) => {
const nestedResult = nested(laterCode, name, key, location, subKey !== '' ? subKey : 'i' + index, isArray)
const testSerializer = getTestSerializer(location.schema.format)
const testValue = testSerializer !== undefined ? `${testSerializer}(obj${accessor}, true)` : `obj${accessor}`
// see comment on anyOf about dereferencing the schema before calling ajv.validate

const schemaKey = location.schema.$id || randomUUID()
ajvInstance.addSchema(location.schema, schemaKey)

code += `
${index === 0 ? 'if' : 'else if'}(ajv.validate("${schemaKey}", ${testValue}))
${nestedResult.code}
`
laterCode = nestedResult.laterCode
})

if (!isArray) {
code += `
Expand Down