@@ -1211,23 +1211,25 @@ function buildValue (laterCode, locationPath, input, location) {
1211
1211
break
1212
1212
default :
1213
1213
if ( Array . isArray ( type ) ) {
1214
- const nullIndex = type . indexOf ( 'null' )
1215
- const sortedTypes = nullIndex !== - 1 ? [ type [ nullIndex ] ] . concat ( type . slice ( 0 , nullIndex ) ) . concat ( type . slice ( nullIndex + 1 ) ) : type
1214
+ let sortedTypes = type
1215
+ const nullable = schema . nullable === true || type . includes ( 'null' )
1216
+
1217
+ if ( nullable ) {
1218
+ sortedTypes = sortedTypes . filter ( type => type !== 'null' )
1219
+ code += `
1220
+ if (${ input } === null) {
1221
+ json += null
1222
+ } else {`
1223
+ }
1224
+
1216
1225
sortedTypes . forEach ( ( type , index ) => {
1217
1226
const statement = index === 0 ? 'if' : 'else if'
1218
1227
const tempSchema = Object . assign ( { } , schema , { type } )
1219
1228
const nestedResult = buildValue ( laterCode , locationPath , input , mergeLocation ( location , { schema : tempSchema } ) )
1220
1229
switch ( type ) {
1221
1230
case 'string' : {
1222
1231
code += `
1223
- ${ statement } (${ input } === null || typeof ${ input } === "${ type } " || ${ input } instanceof Date || typeof ${ input } .toISOString === "function" || ${ input } instanceof RegExp || (typeof ${ input } === "object" && Object.hasOwnProperty.call(${ input } , "toString")))
1224
- ${ nestedResult . code }
1225
- `
1226
- break
1227
- }
1228
- case 'null' : {
1229
- code += `
1230
- ${ statement } (${ input } == null)
1232
+ ${ statement } (${ input } === null || typeof ${ input } === "${ type } " || ${ input } instanceof Date || ${ input } instanceof RegExp || (typeof ${ input } === "object" && Object.hasOwnProperty.call(${ input } , "toString")))
1231
1233
${ nestedResult . code }
1232
1234
`
1233
1235
break
@@ -1246,16 +1248,9 @@ function buildValue (laterCode, locationPath, input, location) {
1246
1248
`
1247
1249
break
1248
1250
}
1249
- case 'number' : {
1250
- code += `
1251
- ${ statement } (isNaN(${ input } ) === false)
1252
- ${ nestedResult . code }
1253
- `
1254
- break
1255
- }
1256
1251
default : {
1257
1252
code += `
1258
- ${ statement } (typeof ${ input } === "${ type } ")
1253
+ ${ statement } (typeof ${ input } === "${ type } " || ${ input } === null )
1259
1254
${ nestedResult . code }
1260
1255
`
1261
1256
break
@@ -1264,8 +1259,14 @@ function buildValue (laterCode, locationPath, input, location) {
1264
1259
laterCode = nestedResult . laterCode
1265
1260
} )
1266
1261
code += `
1267
- else json+= null
1262
+ else throw new Error(\`The value $\{JSON.stringify( ${ input } )} does not match schema definition.\`)
1268
1263
`
1264
+
1265
+ if ( nullable ) {
1266
+ code += `
1267
+ }
1268
+ `
1269
+ }
1269
1270
} else {
1270
1271
throw new Error ( `${ type } unsupported` )
1271
1272
}
0 commit comments