Skip to content

Commit

Permalink
fix: coercion should skip rendering altogether
Browse files Browse the repository at this point in the history
This helps avoiding useless allocations. It also causes required
fields checks to be skipped entirely as those are done at rendering.

see: #670
  • Loading branch information
rhighs committed Jan 5, 2024
1 parent d4b9b06 commit 9552bb5
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 32 deletions.
27 changes: 3 additions & 24 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -559,23 +559,13 @@ function buildObject (context, location) {

let functionCode = `
`
let checkNullableCode = `
`

const nullable = schema.nullable === true
if (!nullable) {
checkNullableCode = `
if (obj === null) {
obj = {}
}
`
}

functionCode += `
// ${schemaRef}
function ${functionName} (input) {
let obj = ${toJSON('input')}
${checkNullableCode}
const obj = ${toJSON('input')}
${!nullable ? 'if (obj === null) return \'{}\'' : ''}
${buildInnerObject(context, location)}
}
Expand Down Expand Up @@ -609,25 +599,14 @@ function buildArray (context, location) {
schemaRef = schemaRef.replace(context.rootSchemaId, '')
}

let checkNullableCode = `
`

let functionCode = `
function ${functionName} (obj) {
// ${schemaRef}
`

const nullable = schema.nullable === true
if (!nullable) {
checkNullableCode = `
if (obj === null) {
obj = []
}
`
}

functionCode += `
${checkNullableCode}
${!nullable ? 'if (obj === null) return \'[]\'' : ''}
if (!Array.isArray(obj)) {
throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`)
}
Expand Down
11 changes: 3 additions & 8 deletions test/toJSON.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ test('on non nullable null object it should coerce to {}', (t) => {
t.equal(result, '{}')
})

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

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

try {
stringify(null)
t.fail('stringify should throw for missing required fields')
} catch (err) {
const message = err.message
t.equal(message, '"product" is required!')
}
const result = stringify(null)
t.equal(result, '{}')
})

0 comments on commit 9552bb5

Please sign in to comment.