Skip to content

Commit

Permalink
throw an error on non-nullable schema receiving null input
Browse files Browse the repository at this point in the history
  • Loading branch information
rhighs committed Dec 27, 2023
1 parent 6de8c6c commit 14bcc09
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
14 changes: 14 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -560,10 +560,24 @@ function buildObject (context, location) {
let functionCode = `
`

let checkNullableCode = `
`
const nullable = schema.nullable === true
if (!nullable) {
// use schemaRef in the hope there's anything useful for which schema is detecting the issue
checkNullableCode += `
if (obj === null) {
throw new Error('schema: ${schemaRef} is not nullable, received null input!')
}
`
}

functionCode += `
// ${schemaRef}
function ${functionName} (input) {
const obj = ${toJSON('input')}
${checkNullableCode}
${buildInnerObject(context, location)}
}
`
Expand Down
26 changes: 26 additions & 0 deletions test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,32 @@ test('render a double quote as JSON /2', (t) => {
t.ok(validate(JSON.parse(output)), 'valid schema')
})

test('should error on non-nullable', t => {
t.plan(1)
const schema = {
title: 'non-nullable schema error',
type: 'object',
properties: {
firstName: {
type: 'string'
},
lastName: {
type: 'string'
}
},
required: ['firstName', 'lastName']
}

try {
const stringify = build(schema)
stringify(null)
t.fail('stringify should throw for null doc validated on non-nullable schema')
} catch (err) {
const message = err.message
t.equal(message, 'schema: # is not nullable, received null input!')
}
})

test('render a long string', (t) => {
t.plan(2)

Expand Down

0 comments on commit 14bcc09

Please sign in to comment.