From e40cc230e4eefad4cdac11bb68ad6153aca5dceb Mon Sep 17 00:00:00 2001 From: Florian Reinhart Date: Mon, 19 Feb 2018 10:44:27 +0100 Subject: [PATCH] Fix code generation for anyOf when containing a nested object (#74) --- index.js | 4 +++- test/anyof.test.js | 44 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 3894610d..cf3dc7f2 100644 --- a/index.js +++ b/index.js @@ -609,10 +609,12 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe case undefined: if ('anyOf' in schema) { schema.anyOf.forEach((s, index) => { + var nestedResult = nested(laterCode, name, key, s, externalSchema, fullSchema, subKey) code += ` ${index === 0 ? 'if' : 'else if'}(ajv.validate(${require('util').inspect(s, {depth: null})}, obj${accessor})) - ${nested(laterCode, name, key, s, externalSchema, fullSchema, subKey).code} + ${nestedResult.code} ` + laterCode = nestedResult.laterCode }) code += ` else json+= null diff --git a/test/anyof.test.js b/test/anyof.test.js index af008c1a..08ec6d48 100644 --- a/test/anyof.test.js +++ b/test/anyof.test.js @@ -11,7 +11,7 @@ test('object with multiple types field', (t) => { type: 'object', properties: { str: { - 'anyOf': [{ + anyOf: [{ type: 'string' }, { type: 'boolean' @@ -39,3 +39,45 @@ test('object with multiple types field', (t) => { t.fail() } }) + +test('object with field of type object or null', (t) => { + t.plan(2) + + const schema = { + title: 'object with field of type object or null', + type: 'object', + properties: { + prop: { + anyOf: [{ + type: 'object', + properties: { + str: { + type: 'string' + } + } + }, { + type: 'null' + }] + } + } + } + const stringify = build(schema) + + try { + const value = stringify({ + prop: null + }) + t.is(value, '{"prop":null}') + } catch (e) { + t.fail() + } + + try { + const value = stringify({ + prop: {str: 'string'} + }) + t.is(value, '{"prop":{"str":"string"}}') + } catch (e) { + t.fail() + } +})