Skip to content

Commit 74413ff

Browse files
mjwwitmcollina
authored andcommitted
Fix serialization of schemas using nested anyOfs containing multiple objects (fixes #155) (#157)
1 parent 9f76520 commit 74413ff

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -881,7 +881,7 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe
881881
case undefined:
882882
if ('anyOf' in schema) {
883883
schema.anyOf.forEach((s, index) => {
884-
var nestedResult = nested(laterCode, name, key, s, externalSchema, fullSchema, subKey)
884+
var nestedResult = nested(laterCode, name, key, s, externalSchema, fullSchema, subKey !== undefined ? subKey : 'i' + index)
885885
code += `
886886
${index === 0 ? 'if' : 'else if'}(ajv.validate(${require('util').inspect(s, { depth: null })}, obj${accessor}))
887887
${nestedResult.code}

test/anyof.test.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,49 @@ test('object with field of type string and coercion enable ', (t) => {
185185
t.fail()
186186
}
187187
})
188+
189+
test('object with field with type union of multiple objects', (t) => {
190+
t.plan(2)
191+
192+
const schema = {
193+
title: 'object with anyOf property value containing objects',
194+
type: 'object',
195+
properties: {
196+
anyOfSchema: {
197+
anyOf: [
198+
{
199+
type: 'object',
200+
properties: {
201+
baz: { type: 'number' }
202+
},
203+
required: ['baz']
204+
},
205+
{
206+
type: 'object',
207+
properties: {
208+
bar: { type: 'string' }
209+
},
210+
required: ['bar']
211+
}
212+
]
213+
}
214+
},
215+
required: ['anyOfSchema']
216+
}
217+
218+
const stringify = build(schema)
219+
220+
try {
221+
const value = stringify({ anyOfSchema: { baz: 5 } })
222+
t.is(value, '{"anyOfSchema":{"baz":5}}')
223+
} catch (e) {
224+
t.fail()
225+
}
226+
227+
try {
228+
const value = stringify({ anyOfSchema: { bar: 'foo' } })
229+
t.is(value, '{"anyOfSchema":{"bar":"foo"}}')
230+
} catch (e) {
231+
t.fail()
232+
}
233+
})

0 commit comments

Comments
 (0)