Skip to content

Commit e49e80c

Browse files
committed
fix: coercion should skip rendering altogether
This helps avoiding useless allocations. It also causes required fields checks to be skipped entirely as those are done at rendering. see: fastify#670
1 parent d4b9b06 commit e49e80c

File tree

2 files changed

+6
-32
lines changed

2 files changed

+6
-32
lines changed

index.js

Lines changed: 3 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -559,23 +559,13 @@ function buildObject (context, location) {
559559

560560
let functionCode = `
561561
`
562-
let checkNullableCode = `
563-
`
564562

565563
const nullable = schema.nullable === true
566-
if (!nullable) {
567-
checkNullableCode = `
568-
if (obj === null) {
569-
obj = {}
570-
}
571-
`
572-
}
573-
574564
functionCode += `
575565
// ${schemaRef}
576566
function ${functionName} (input) {
577-
let obj = ${toJSON('input')}
578-
${checkNullableCode}
567+
${!nullable ? 'if (input === null) return \'{}\'' : ''}
568+
const obj = ${toJSON('input')}
579569
580570
${buildInnerObject(context, location)}
581571
}
@@ -609,25 +599,14 @@ function buildArray (context, location) {
609599
schemaRef = schemaRef.replace(context.rootSchemaId, '')
610600
}
611601

612-
let checkNullableCode = `
613-
`
614-
615602
let functionCode = `
616603
function ${functionName} (obj) {
617604
// ${schemaRef}
618605
`
619606

620607
const nullable = schema.nullable === true
621-
if (!nullable) {
622-
checkNullableCode = `
623-
if (obj === null) {
624-
obj = []
625-
}
626-
`
627-
}
628-
629608
functionCode += `
630-
${checkNullableCode}
609+
${!nullable ? 'if (obj === null) return \'[]\'' : ''}
631610
if (!Array.isArray(obj)) {
632611
throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`)
633612
}

test/toJSON.test.js

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ test('on non nullable null object it should coerce to {}', (t) => {
177177
t.equal(result, '{}')
178178
})
179179

180-
test('on non-nullable null object with required fields it should throw complaining missing required fields', (t) => {
180+
test('on non-nullable null object it should skip rendering, skipping required fields checks', (t) => {
181181
t.plan(1)
182182

183183
const stringify = build({
@@ -198,11 +198,6 @@ test('on non-nullable null object with required fields it should throw complaini
198198
required: ['product']
199199
})
200200

201-
try {
202-
stringify(null)
203-
t.fail('stringify should throw for missing required fields')
204-
} catch (err) {
205-
const message = err.message
206-
t.equal(message, '"product" is required!')
207-
}
201+
const result = stringify(null)
202+
t.equal(result, '{}')
208203
})

0 commit comments

Comments
 (0)