Skip to content

Fix serialization of nested objects #80

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions test/nestedObjects.test.js
Original file line number Diff line number Diff line change
@@ -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()
}
})