Skip to content

Commit 1312e83

Browse files
fix: remove nested if/then duplicate serialization (#471)
1 parent 49d820a commit 1312e83

File tree

2 files changed

+42
-7
lines changed

2 files changed

+42
-7
lines changed

index.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -523,8 +523,9 @@ function addIfThenElse (location) {
523523

524524
if (thenSchema.if && thenSchema.then) {
525525
code += addIfThenElse(thenLocation)
526+
} else {
527+
code += buildInnerObject(thenLocation)
526528
}
527-
code += buildInnerObject(thenLocation)
528529
code += `
529530
}
530531
`
@@ -538,8 +539,9 @@ function addIfThenElse (location) {
538539

539540
if (elseSchema.if && elseSchema.then) {
540541
code += addIfThenElse(elseLocation)
542+
} else {
543+
code += buildInnerObject(elseLocation)
541544
}
542-
code += buildInnerObject(elseLocation)
543545
code += `
544546
}
545547
`
@@ -582,15 +584,13 @@ function buildObject (location) {
582584
var addComma = false
583585
`
584586

585-
let rCode
586587
if (schema.if && schema.then) {
587-
rCode = addIfThenElse(location)
588+
functionCode += addIfThenElse(location)
588589
} else {
589-
rCode = buildInnerObject(location)
590+
functionCode += buildInnerObject(location)
590591
}
591592

592-
// Removes the comma if is the last element of the string (in case there are not properties)
593-
functionCode += `${rCode}
593+
functionCode += `
594594
json += '}'
595595
return json
596596
}

test/if-then-else.test.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,3 +333,38 @@ t.test('if-then-else', t => {
333333

334334
t.end()
335335
})
336+
337+
t.test('nested if/then', t => {
338+
t.plan(2)
339+
340+
const schema = {
341+
type: 'object',
342+
properties: { a: { type: 'string' } },
343+
if: {
344+
type: 'object',
345+
properties: { foo: { type: 'string' } }
346+
},
347+
then: {
348+
properties: { bar: { type: 'string' } },
349+
if: {
350+
type: 'object',
351+
properties: { foo1: { type: 'string' } }
352+
},
353+
then: {
354+
properties: { bar1: { type: 'string' } }
355+
}
356+
}
357+
}
358+
359+
const stringify = build(schema)
360+
361+
t.equal(
362+
stringify({ a: 'A', foo: 'foo', bar: 'bar' }),
363+
JSON.stringify({ a: 'A', bar: 'bar' })
364+
)
365+
366+
t.equal(
367+
stringify({ a: 'A', foo: 'foo', bar: 'bar', foo1: 'foo1', bar1: 'bar1' }),
368+
JSON.stringify({ a: 'A', bar: 'bar', bar1: 'bar1' })
369+
)
370+
})

0 commit comments

Comments
 (0)