Skip to content

Commit b5e49ae

Browse files
florianreinhartmcollina
authored andcommitted
Fix serialization of nested objects when using additionalProperties or patternProperties (#80)
1 parent 82c9087 commit b5e49ae

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

index.js

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,7 @@ function build (schema, options) {
2424
var code = `
2525
'use strict'
2626
`
27-
// used to support patternProperties and additionalProperties
28-
// they need to check if a field belongs to the properties in the schema
29-
code += `
30-
var properties = ${JSON.stringify(schema.properties)} || {}
31-
`
27+
3228
code += `
3329
${$asString.toString()}
3430
${$asStringSmall.toString()}
@@ -218,6 +214,7 @@ function $asStringSmall (str) {
218214
function addPatternProperties (schema, externalSchema, fullSchema) {
219215
var pp = schema.patternProperties
220216
var code = `
217+
var properties = ${JSON.stringify(schema.properties)} || {}
221218
var keys = Object.keys(obj)
222219
for (var i = 0; i < keys.length; i++) {
223220
if (properties[keys[i]]) continue
@@ -368,6 +365,7 @@ function additionalProperty (schema, externalSchema, fullSchema) {
368365

369366
function addAdditionalProperties (schema, externalSchema, fullSchema) {
370367
return `
368+
var properties = ${JSON.stringify(schema.properties)} || {}
371369
var keys = Object.keys(obj)
372370
for (var i = 0; i < keys.length; i++) {
373371
if (properties[keys[i]]) continue

test/nestedObjects.test.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict'
2+
3+
const test = require('tap').test
4+
const build = require('..')
5+
6+
test('nested objects with same properties', (t) => {
7+
t.plan(1)
8+
9+
const schema = {
10+
title: 'nested objects with same properties',
11+
type: 'object',
12+
properties: {
13+
stringProperty: {
14+
type: 'string'
15+
},
16+
objectProperty: {
17+
type: 'object',
18+
additionalProperties: true
19+
}
20+
}
21+
}
22+
const stringify = build(schema)
23+
24+
try {
25+
const value = stringify({
26+
stringProperty: 'string1',
27+
objectProperty: {
28+
stringProperty: 'string2',
29+
numberProperty: 42
30+
}
31+
})
32+
t.is(value, '{"stringProperty":"string1","objectProperty":{"stringProperty":"string2","numberProperty":42}}')
33+
} catch (e) {
34+
t.fail()
35+
}
36+
})

0 commit comments

Comments
 (0)