@@ -1211,23 +1211,25 @@ function buildValue (laterCode, locationPath, input, location) {
12111211 break
12121212 default :
12131213 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+
12161225 sortedTypes . forEach ( ( type , index ) => {
12171226 const statement = index === 0 ? 'if' : 'else if'
12181227 const tempSchema = Object . assign ( { } , schema , { type } )
12191228 const nestedResult = buildValue ( laterCode , locationPath , input , mergeLocation ( location , { schema : tempSchema } ) )
12201229 switch ( type ) {
12211230 case 'string' : {
12221231 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")))
12311233 ${ nestedResult . code }
12321234 `
12331235 break
@@ -1246,16 +1248,9 @@ function buildValue (laterCode, locationPath, input, location) {
12461248 `
12471249 break
12481250 }
1249- case 'number' : {
1250- code += `
1251- ${ statement } (isNaN(${ input } ) === false)
1252- ${ nestedResult . code }
1253- `
1254- break
1255- }
12561251 default : {
12571252 code += `
1258- ${ statement } (typeof ${ input } === "${ type } ")
1253+ ${ statement } (typeof ${ input } === "${ type } " || ${ input } === null )
12591254 ${ nestedResult . code }
12601255 `
12611256 break
@@ -1264,8 +1259,14 @@ function buildValue (laterCode, locationPath, input, location) {
12641259 laterCode = nestedResult . laterCode
12651260 } )
12661261 code += `
1267- else json+= null
1262+ else throw new Error(\`The value $\{JSON.stringify( ${ input } )} does not match schema definition.\`)
12681263 `
1264+
1265+ if ( nullable ) {
1266+ code += `
1267+ }
1268+ `
1269+ }
12691270 } else {
12701271 throw new Error ( `${ type } unsupported` )
12711272 }
0 commit comments