Skip to content

Commit b909e00

Browse files
authored
fix: passing null object to type array defaults to empty array (#249) (#265)
* fix: passing null object to type array defaults to empty array (#249) * test: added test with default field in schema * test: removed redundant test * fix: now we throw an error with a clear message if receiving a null on array type
1 parent 4eaaa0c commit b909e00

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

index.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -937,7 +937,7 @@ function buildObject (location, code, name) {
937937
return code
938938
}
939939

940-
function buildArray (location, code, name) {
940+
function buildArray (location, code, name, key = null) {
941941
var schema = location.schema
942942
code += `
943943
function ${name} (obj) {
@@ -988,6 +988,14 @@ function buildArray (location, code, name) {
988988
result = nested(laterCode, name, '[i]', mergeLocation(location, { schema: schema.items }), undefined, true)
989989
}
990990

991+
if (key) {
992+
code += `
993+
if(!Array.isArray(obj)) {
994+
throw new TypeError(\`Property '${key}' should be of type array, received '$\{obj}' instead.\`)
995+
}
996+
`
997+
}
998+
991999
code += `
9921000
var l = obj.length
9931001
var w = l - 1
@@ -1131,7 +1139,7 @@ function nested (laterCode, name, key, location, subKey, isArray) {
11311139
break
11321140
case 'array':
11331141
funcName = asFuncName('$arr' + name + key + subKey) // eslint-disable-line
1134-
laterCode = buildArray(location, laterCode, funcName)
1142+
laterCode = buildArray(location, laterCode, funcName, key)
11351143
code += `
11361144
json += ${funcName}(obj${accessor})
11371145
`

test/typesArray.test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,3 +417,21 @@ test('object that is simultaneously a string and a json switched', (t) => {
417417
const valueObj = stringify({ simultaneously: { foo: likeObjectId } })
418418
t.is(valueObj, '{"simultaneously":{"foo":"hello"}}')
419419
})
420+
421+
test('should throw an error when type is array and object is null', (t) => {
422+
t.plan(1)
423+
const schema = {
424+
type: 'object',
425+
properties: {
426+
arr: {
427+
type: 'array',
428+
items: {
429+
type: 'number'
430+
}
431+
}
432+
}
433+
}
434+
435+
const stringify = build(schema)
436+
t.throws(() => stringify({ arr: null }), new TypeError('Property \'arr\' should be of type array, received \'null\' instead.'))
437+
})

0 commit comments

Comments
 (0)