Skip to content

Commit e37db95

Browse files
refactor: combine oneOf and anyOf handlers (#440)
1 parent 798ec60 commit e37db95

File tree

1 file changed

+3
-25
lines changed

1 file changed

+3
-25
lines changed

index.js

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1192,11 +1192,10 @@ function nested (laterCode, name, key, location, subKey, isArray) {
11921192
code += `json += ${funcName}(obj${accessor})`
11931193
break
11941194
case undefined:
1195-
funcName = 'serializer.asNull.bind(serializer)'
1196-
if ('anyOf' in schema) {
1195+
if (schema.anyOf || schema.oneOf) {
11971196
// beware: dereferenceOfRefs has side effects and changes schema.anyOf
1198-
const anyOfLocations = dereferenceOfRefs(location, 'anyOf')
1199-
anyOfLocations.forEach((location, index) => {
1197+
const locations = dereferenceOfRefs(location, schema.anyOf ? 'anyOf' : 'oneOf')
1198+
locations.forEach((location, index) => {
12001199
const nestedResult = nested(laterCode, name, key, location, subKey !== '' ? subKey : 'i' + index, isArray)
12011200
// We need a test serializer as the String serializer will not work with
12021201
// date/time ajv validations
@@ -1221,27 +1220,6 @@ function nested (laterCode, name, key, location, subKey, isArray) {
12211220
`
12221221
laterCode = nestedResult.laterCode
12231222
})
1224-
code += `
1225-
else json+= null
1226-
`
1227-
} else if ('oneOf' in schema) {
1228-
// beware: dereferenceOfRefs has side effects and changes schema.oneOf
1229-
const oneOfLocations = dereferenceOfRefs(location, 'oneOf')
1230-
oneOfLocations.forEach((location, index) => {
1231-
const nestedResult = nested(laterCode, name, key, location, subKey !== '' ? subKey : 'i' + index, isArray)
1232-
const testSerializer = getTestSerializer(location.schema.format)
1233-
const testValue = testSerializer !== undefined ? `${testSerializer}(obj${accessor}, true)` : `obj${accessor}`
1234-
// see comment on anyOf about dereferencing the schema before calling ajv.validate
1235-
1236-
const schemaKey = location.schema.$id || randomUUID()
1237-
ajvInstance.addSchema(location.schema, schemaKey)
1238-
1239-
code += `
1240-
${index === 0 ? 'if' : 'else if'}(ajv.validate("${schemaKey}", ${testValue}))
1241-
${nestedResult.code}
1242-
`
1243-
laterCode = nestedResult.laterCode
1244-
})
12451223

12461224
if (!isArray) {
12471225
code += `

0 commit comments

Comments
 (0)