Skip to content

Commit e4f6836

Browse files
florianreinhartdelvedor
authored andcommitted
Fix code generation for anyOf when containing a nested object (#74) (#76)
1 parent 94ebe64 commit e4f6836

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -609,10 +609,12 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe
609609
case undefined:
610610
if ('anyOf' in schema) {
611611
schema.anyOf.forEach((s, index) => {
612+
var nestedResult = nested(laterCode, name, key, s, externalSchema, fullSchema, subKey)
612613
code += `
613614
${index === 0 ? 'if' : 'else if'}(ajv.validate(${require('util').inspect(s, {depth: null})}, obj${accessor}))
614-
${nested(laterCode, name, key, s, externalSchema, fullSchema, subKey).code}
615+
${nestedResult.code}
615616
`
617+
laterCode = nestedResult.laterCode
616618
})
617619
code += `
618620
else json+= null

test/anyof.test.js

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ test('object with multiple types field', (t) => {
1111
type: 'object',
1212
properties: {
1313
str: {
14-
'anyOf': [{
14+
anyOf: [{
1515
type: 'string'
1616
}, {
1717
type: 'boolean'
@@ -39,3 +39,45 @@ test('object with multiple types field', (t) => {
3939
t.fail()
4040
}
4141
})
42+
43+
test('object with field of type object or null', (t) => {
44+
t.plan(2)
45+
46+
const schema = {
47+
title: 'object with field of type object or null',
48+
type: 'object',
49+
properties: {
50+
prop: {
51+
anyOf: [{
52+
type: 'object',
53+
properties: {
54+
str: {
55+
type: 'string'
56+
}
57+
}
58+
}, {
59+
type: 'null'
60+
}]
61+
}
62+
}
63+
}
64+
const stringify = build(schema)
65+
66+
try {
67+
const value = stringify({
68+
prop: null
69+
})
70+
t.is(value, '{"prop":null}')
71+
} catch (e) {
72+
t.fail()
73+
}
74+
75+
try {
76+
const value = stringify({
77+
prop: {str: 'string'}
78+
})
79+
t.is(value, '{"prop":{"str":"string"}}')
80+
} catch (e) {
81+
t.fail()
82+
}
83+
})

0 commit comments

Comments
 (0)