Skip to content

Commit

Permalink
fix: coerce to default type on strict null eq.
Browse files Browse the repository at this point in the history
array -> []
object -> []
  • Loading branch information
rhighs committed Dec 30, 2023
1 parent 6d50c95 commit d4b9b06
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,8 @@ Otherwise, instead of raising an error, null values will be coerced as follows:
- `number` -> `0`
- `string` -> `""`
- `boolean` -> `false`
- `object` -> `{}`
- `array` -> `[]`

<a name="largearrays"></a>
#### Large Arrays
Expand Down
27 changes: 26 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -559,11 +559,23 @@ 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) {
const obj = ${toJSON('input')} || {}
let obj = ${toJSON('input')}
${checkNullableCode}
${buildInnerObject(context, location)}
}
Expand Down Expand Up @@ -597,12 +609,25 @@ 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}
if (!Array.isArray(obj)) {
throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`)
}
Expand Down
5 changes: 3 additions & 2 deletions test/typesArray.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ test('class instance that is simultaneously a string and a json', (t) => {
t.equal(valueObj, '{"simultaneously":{"foo":"hello"}}')
})

test('should throw an error when type is array and object is null', (t) => {
test('should not throw an error when type is array and object is null, it should instead coerce to []', (t) => {
t.plan(1)
const schema = {
type: 'object',
Expand All @@ -482,7 +482,8 @@ test('should throw an error when type is array and object is null', (t) => {
}

const stringify = build(schema)
t.throws(() => stringify({ arr: null }), new TypeError('The value of \'#/properties/arr\' does not match schema definition.'))
const result = stringify({ arr: null })
t.equal(result, JSON.stringify({ arr: [] }))
})

test('should throw an error when type is array and object is not an array', (t) => {
Expand Down

0 comments on commit d4b9b06

Please sign in to comment.