From 14bcc09b3e396b801635719ea988e4385f864c65 Mon Sep 17 00:00:00 2001 From: roberto montalti Date: Wed, 27 Dec 2023 22:09:45 +0100 Subject: [PATCH] throw an error on non-nullable schema receiving null input --- index.js | 14 ++++++++++++++ test/basic.test.js | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/index.js b/index.js index ea435369..40cf1e74 100644 --- a/index.js +++ b/index.js @@ -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)} } ` diff --git a/test/basic.test.js b/test/basic.test.js index bd47ac7d..a9e339fc 100644 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -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)