From 77d06933fb4f5d2f809c8b485f4f51555a91288a Mon Sep 17 00:00:00 2001 From: Florian Reinhart Date: Thu, 1 Mar 2018 13:33:26 +0100 Subject: [PATCH] Fix serialization of nested objects when using additionalProperties or patternProperties --- index.js | 8 +++----- test/nestedObjects.test.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) create mode 100644 test/nestedObjects.test.js diff --git a/index.js b/index.js index a61c2b26..422852d8 100644 --- a/index.js +++ b/index.js @@ -24,11 +24,7 @@ function build (schema, options) { var code = ` 'use strict' ` - // used to support patternProperties and additionalProperties - // they need to check if a field belongs to the properties in the schema - code += ` - var properties = ${JSON.stringify(schema.properties)} || {} - ` + code += ` ${$asString.toString()} ${$asStringSmall.toString()} @@ -218,6 +214,7 @@ function $asStringSmall (str) { function addPatternProperties (schema, externalSchema, fullSchema) { var pp = schema.patternProperties var code = ` + var properties = ${JSON.stringify(schema.properties)} || {} var keys = Object.keys(obj) for (var i = 0; i < keys.length; i++) { if (properties[keys[i]]) continue @@ -368,6 +365,7 @@ function additionalProperty (schema, externalSchema, fullSchema) { function addAdditionalProperties (schema, externalSchema, fullSchema) { return ` + var properties = ${JSON.stringify(schema.properties)} || {} var keys = Object.keys(obj) for (var i = 0; i < keys.length; i++) { if (properties[keys[i]]) continue diff --git a/test/nestedObjects.test.js b/test/nestedObjects.test.js new file mode 100644 index 00000000..0f448c5f --- /dev/null +++ b/test/nestedObjects.test.js @@ -0,0 +1,36 @@ +'use strict' + +const test = require('tap').test +const build = require('..') + +test('nested objects with same properties', (t) => { + t.plan(1) + + const schema = { + title: 'nested objects with same properties', + type: 'object', + properties: { + stringProperty: { + type: 'string' + }, + objectProperty: { + type: 'object', + additionalProperties: true + } + } + } + const stringify = build(schema) + + try { + const value = stringify({ + stringProperty: 'string1', + objectProperty: { + stringProperty: 'string2', + numberProperty: 42 + } + }) + t.is(value, '{"stringProperty":"string1","objectProperty":{"stringProperty":"string2","numberProperty":42}}') + } catch (e) { + t.fail() + } +})