Skip to content

Commit 2148a38

Browse files
authored
Merge pull request #26 from fastify/nested-additional-properties
Optional properties support
2 parents ec9858e + de89496 commit 2148a38

File tree

2 files changed

+59
-2
lines changed

2 files changed

+59
-2
lines changed

index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ function build (schema, options) {
1111
// used to support patternProperties and additionalProperties
1212
// they need to check if a field belongs to the properties in the schema
1313
code += `
14-
const properties = ${JSON.stringify(schema.properties)}
14+
const properties = ${JSON.stringify(schema.properties)} || {}
1515
`
1616
code += `
1717
${$asString.toString()}
@@ -264,7 +264,7 @@ function buildObject (schema, code, name, externalSchema, fullSchema) {
264264

265265
var laterCode = ''
266266

267-
Object.keys(schema.properties).forEach((key, i, a) => {
267+
Object.keys(schema.properties || {}).forEach((key, i, a) => {
268268
// Using obj.key !== undefined instead of obj.hasOwnProperty(prop) for perf reasons,
269269
// see https://github.com/mcollina/fast-json-stringify/pull/3 for discussion.
270270
code += `

test/additionalProperties.test.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,3 +180,60 @@ test('additionalProperties - throw on unknown type', (t) => {
180180
t.pass()
181181
}
182182
})
183+
184+
test('nested additionalProperties', (t) => {
185+
t.plan(1)
186+
const stringify = build({
187+
title: 'additionalProperties',
188+
type: 'array',
189+
items: {
190+
type: 'object',
191+
properties: {
192+
ap: {
193+
type: 'object',
194+
additionalProperties: { type: 'string' }
195+
}
196+
}
197+
}
198+
})
199+
200+
let obj = [{ ap: { value: 'string' } }]
201+
t.equal('[{"ap":{"value":"string"}}]', stringify(obj))
202+
})
203+
204+
test('very nested additionalProperties', (t) => {
205+
t.plan(1)
206+
const stringify = build({
207+
title: 'additionalProperties',
208+
type: 'array',
209+
items: {
210+
type: 'object',
211+
properties: {
212+
ap: {
213+
type: 'object',
214+
properties: {
215+
nested: {
216+
type: 'object',
217+
properties: {
218+
moarNested: {
219+
type: 'object',
220+
properties: {
221+
finally: {
222+
type: 'object',
223+
additionalProperties: {
224+
type: 'string'
225+
}
226+
}
227+
}
228+
}
229+
}
230+
}
231+
}
232+
}
233+
}
234+
}
235+
})
236+
237+
let obj = [{ ap: { nested: { moarNested: { finally: { value: 'str' } } } } }]
238+
t.equal('[{"ap":{"nested":{"moarNested":{"finally":{"value":"str"}}}}}]', stringify(obj))
239+
})

0 commit comments

Comments
 (0)