Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,11 @@ Otherwise, instead of raising an error, null values will be coerced as follows:
- `object` -> `{}`
- `array` -> `[]`

The same applies to `undefined` when it is an item of an array or the value
passed to `stringify()`. A property of an object set to `undefined` is skipped
instead, as described in <a href="#missingFields">Missing fields</a>, and a
`required` one still throws.

<a name="largearrays"></a>
#### Large Arrays

Expand Down
28 changes: 14 additions & 14 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1018,7 +1018,7 @@ function buildObject (context, location, input) {
// ${asComment(schemaRef)}
function ${functionName} (input) {
const obj = ${toJSON('input')}
if (obj === null) return ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_OBJECT'}
if (obj == null) return ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_OBJECT'}
let json = ''

${buildInnerObject(context, location, 'obj', true)}
Expand All @@ -1033,7 +1033,7 @@ function buildObject (context, location, input) {
const objVar = `obj_${context.uid++}`
const code = `
const ${objVar} = ${toJSON(input)}
if (${objVar} === null) {
if (${objVar} == null) {
json += ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_OBJECT'}
} else {
${buildInnerObject(context, location, objVar)}
Expand Down Expand Up @@ -1149,7 +1149,7 @@ function buildArray (context, location, input) {
`

functionCode += `
if (obj === null) return ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_ARRAY'}
if (obj == null) return ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_ARRAY'}
if (!Array.isArray(obj)) {
throw new TypeError(${JSON.stringify(`The value of '${schemaRef}' does not match schema definition.`)})
}
Expand Down Expand Up @@ -1274,7 +1274,7 @@ function buildArray (context, location, input) {
const objVar = `obj_${context.uid++}`
let inlinedCode = `
const ${objVar} = ${input}
if (${objVar} === null) {
if (${objVar} == null) {
json += ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_ARRAY'}
} else if (!Array.isArray(${objVar})) {
throw new TypeError(${JSON.stringify(`The value of '${safeSchemaRef}' does not match schema definition.`)})
Expand Down Expand Up @@ -1368,11 +1368,11 @@ function buildArrayTypeCondition (type, accessor) {
let condition
switch (type) {
case 'null':
condition = `${accessor} === null`
condition = `${accessor} == null`
break
case 'string':
condition = `typeof ${accessor} === 'string' ||
${accessor} === null ||
${accessor} == null ||
${accessor} instanceof Date ||
${accessor} instanceof RegExp ||
(
Expand Down Expand Up @@ -1432,7 +1432,7 @@ function buildMultiTypeSerializer (context, location, input) {
switch (type) {
case 'null':
code += `
${statement} (${input} === null) {
${statement} (${input} == null) {
${nestedResult}
}
`
Expand All @@ -1441,7 +1441,7 @@ function buildMultiTypeSerializer (context, location, input) {
code += `
${statement}(
typeof ${input} === "string" ||
${input} === null ||
${input} == null ||
${input} instanceof Date ||
${input} instanceof RegExp ||
(
Expand All @@ -1465,7 +1465,7 @@ function buildMultiTypeSerializer (context, location, input) {
}
case 'integer': {
code += `
${statement}(Number.isInteger(${input}) || ${input} === null) {
${statement}(Number.isInteger(${input}) || ${input} == null) {
${nestedResult}
}
`
Expand All @@ -1476,15 +1476,15 @@ function buildMultiTypeSerializer (context, location, input) {
// by this branch and serialized as an object (dropping its items). Exclude
// arrays here so a sibling `array` type in the same `type` list can match.
code += `
${statement}((typeof ${input} === "object" && !Array.isArray(${input})) || ${input} === null) {
${statement}((typeof ${input} === "object" && !Array.isArray(${input})) || ${input} == null) {
${nestedResult}
}
`
break
}
default: {
code += `
${statement}(typeof ${input} === "${type}" || ${input} === null) {
${statement}(typeof ${input} === "${type}" || ${input} == null) {
${nestedResult}
}
`
Expand Down Expand Up @@ -1517,7 +1517,7 @@ function buildSingleTypeSerializer (context, location, input) {
} else {
return `
if (typeof ${input} !== 'string') {
if (${input} === null) {
if (${input} == null) {
json += JSON_STR_EMPTY_STRING
} else if (${input} instanceof Date) {
json += asDateTime(${input})
Expand Down Expand Up @@ -1652,7 +1652,7 @@ function buildConstSerializer (location, input) {

if (hasNullType) {
code += `
if (${input} === null) {
if (${input} == null) {
json += JSON_STR_NULL
} else {
`
Expand Down Expand Up @@ -1905,7 +1905,7 @@ function buildValue (context, location, input) {
const nullable = schema.nullable === true
if (nullable) {
code += `
if (${input} === null) {
if (${input} == null) {
json += JSON_STR_NULL
} else {
`
Expand Down
29 changes: 15 additions & 14 deletions lib/projection.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@
// schemas.
//
// Semantics match the string codegen byte for byte: input.toJSON() honoured,
// `required` missing throws, `undefined` omitted, `default` applied, null
// string -> "", null number -> 0, null object -> {}, Date in a string -> ISO,
// numbers via the asNumber/asInteger rules, booleans via truthiness.
// `required` missing throws, an `undefined` property omitted, `default`
// applied, null or undefined string -> "", number -> 0, object -> {},
// array -> [], Date in a string -> ISO, numbers via the asNumber/asInteger
// rules, booleans via truthiness.

const PRIMITIVES = new Set(['string', 'number', 'integer', 'boolean'])

Expand Down Expand Up @@ -143,15 +144,15 @@ function primitiveExpr (schema, src, pointerIdx) {
const err = `typeMismatch(${pointerIdx})`
const single = primitiveExpr({ ...schema, type: base, nullable: false }, src, pointerIdx)
if (base === 'string') {
return `(${src} === null ? null : (typeof ${src} === 'string' || ${src} instanceof Date || ${src} instanceof RegExp || (typeof ${src} === 'object' && typeof ${src}.toString === 'function' && ${src}.toString !== Object.prototype.toString)) ? ${single} : ${err})`
return `(${src} == null ? null : (typeof ${src} === 'string' || ${src} instanceof Date || ${src} instanceof RegExp || (typeof ${src} === 'object' && typeof ${src}.toString === 'function' && ${src}.toString !== Object.prototype.toString)) ? ${single} : ${err})`
}
if (base === 'number') {
return `(${src} === null ? null : typeof ${src} === 'number' ? ${single} : ${err})`
return `(${src} == null ? null : typeof ${src} === 'number' ? ${single} : ${err})`
}
return `(${src} === null ? null : typeof ${src} === 'boolean' ? ${src} : ${err})`
return `(${src} == null ? null : typeof ${src} === 'boolean' ? ${src} : ${err})`
}
if (schema.nullable === true) {
return `(${src} === null ? null : ${primitiveExpr({ ...schema, nullable: false }, src, pointerIdx)})`
return `(${src} == null ? null : ${primitiveExpr({ ...schema, nullable: false }, src, pointerIdx)})`
}
switch (schema.type) {
case 'string':
Expand Down Expand Up @@ -212,8 +213,8 @@ class Emitter {
const result = this.id('r')
out.push(`${indent}const ${o} = (${src} !== null && typeof ${src} === 'object' && typeof ${src}.toJSON === 'function') ? ${src}.toJSON() : ${src}`)
out.push(`${indent}let ${result}`)
out.push(`${indent}if (${o} === null) {`)
// a null input is written as {} (same as the codegen), or as null when nullable
out.push(`${indent}if (${o} == null) {`)
// a null or undefined input is written as {} (same as the codegen), or as null when nullable
out.push(`${indent} ${result} = ${schema.nullable === true ? 'null' : '{}'}`)
out.push(`${indent}} else {`)
for (const k of requiredList) {
Expand Down Expand Up @@ -268,8 +269,8 @@ class Emitter {
const i = this.id('i')
const result = this.id('r')
out.push(`${indent}let ${result}`)
out.push(`${indent}if (${src} === null) {`)
// a null input is written as [] (same as the codegen), or as null when nullable
out.push(`${indent}if (${src} == null) {`)
// a null or undefined input is written as [] (same as the codegen), or as null when nullable
out.push(`${indent} ${result} = ${schema.nullable === true ? 'null' : '[]'}`)
out.push(`${indent}} else {`)
out.push(`${indent} if (!Array.isArray(${src})) typeMismatch(${this.pointerIndex(schema[POINTER])})`)
Expand Down Expand Up @@ -347,13 +348,13 @@ ${body.join('\n')}
const projectionHelpers = `
const asStringValue = (v) => {
if (typeof v === 'string') return v
if (v === null) return ''
if (v == null) return ''
if (v instanceof Date) return serializer.asDateTimeValue(v)
if (v instanceof RegExp) return v.source
return v.toString()
}
const asDateTimeValue = (v) => {
if (v === null) return ''
if (v == null) return ''
if (v instanceof Date) return serializer.asDateTimeValue(v)
if (typeof v === 'string') return v
throw new Error('The value "' + v + '" cannot be converted to a date-time.')
Expand All @@ -364,7 +365,7 @@ const projectionHelpers = `
const asDateValue = (v) => typeof v === 'string' ? v : serializer.asDate(v).slice(1, -1)
const asTimeValue = (v) => typeof v === 'string' ? v : serializer.asTime(v).slice(1, -1)
const asNumberValue = (v) => {
const num = typeof v === 'number' ? v : Number(v)
const num = typeof v === 'number' ? v : v == null ? 0 : Number(v)
if (num !== num) throw new Error('The value "' + v + '" cannot be converted to a number.')
return (num === Infinity || num === -Infinity) ? null : num
}
Expand Down
14 changes: 10 additions & 4 deletions lib/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ module.exports = class Serializer {
} else if (typeof i === 'bigint') {
return i.toString()
}
if (i == null) {
return '0'
}
/* eslint no-undef: "off" */
const integer = this.parseInteger(i)
// check if number is Infinity or NaN
Expand All @@ -128,6 +131,9 @@ module.exports = class Serializer {
}

asNumber (i) {
if (i == null) {
return '0'
}
// fast cast to number
const num = Number(i)
// check if number is NaN
Expand All @@ -146,7 +152,7 @@ module.exports = class Serializer {
}

asDateTime (date) {
if (date === null) return '""'
if (date == null) return '""'
if (date instanceof Date) {
return asDateTimeString(date)
}
Expand All @@ -157,7 +163,7 @@ module.exports = class Serializer {
}

asDate (date) {
if (date === null) return '""'
if (date == null) return '""'
if (date instanceof Date) {
const year = asYear(date.getFullYear())
if (year === null) {
Expand All @@ -172,7 +178,7 @@ module.exports = class Serializer {
}

asTime (date) {
if (date === null) return '""'
if (date == null) return '""'
if (date instanceof Date) {
const hours = TWO_DIGITS[date.getHours()]
// undefined only for an invalid Date; let toISOString() raise as before
Expand Down Expand Up @@ -241,7 +247,7 @@ module.exports = class Serializer {
if (j > 0) json += ','
if (typeof item === 'string') {
json += asString(item)
} else if (item === null) {
} else if (item == null) {
json += '""'
} else if (item instanceof Date) {
json += asDateTimeString(item)
Expand Down
Loading
Loading