11'use strict'
22
33var fastSafeStringify = require ( 'fast-safe-stringify' )
4+ var Ajv = require ( 'ajv' )
45
56var uglify = null
67var isLong
@@ -87,10 +88,19 @@ function build (schema, options) {
8788 code = uglifyCode ( code )
8889 }
8990
91+ var dependencies = [ ]
92+ var dependenciesName = [ ]
9093 if ( hasAdditionalPropertiesTrue ( schema ) ) {
91- return ( new Function ( 'fastSafeStringify' , code ) ) ( fastSafeStringify )
94+ dependencies . push ( fastSafeStringify )
95+ dependenciesName . push ( 'fastSafeStringify' )
9296 }
93- return ( new Function ( code ) ) ( )
97+ if ( hasAnyOf ( schema ) ) {
98+ dependencies . push ( new Ajv ( ) )
99+ dependenciesName . push ( 'ajv' )
100+ }
101+
102+ dependenciesName . push ( code )
103+ return ( Function . apply ( null , dependenciesName ) . apply ( null , dependencies ) )
94104}
95105
96106function hasAdditionalPropertiesTrue ( schema ) {
@@ -107,6 +117,20 @@ function hasAdditionalPropertiesTrue (schema) {
107117 return false
108118}
109119
120+ function hasAnyOf ( schema ) {
121+ if ( 'anyOf' in schema ) { return true }
122+
123+ var objectKeys = Object . keys ( schema )
124+ for ( var i = 0 ; i < objectKeys . length ; i ++ ) {
125+ var value = schema [ objectKeys [ i ] ]
126+ if ( typeof value === 'object' ) {
127+ if ( hasAnyOf ( value ) ) { return true }
128+ }
129+ }
130+
131+ return false
132+ }
133+
110134function $asNull ( ) {
111135 return 'null'
112136}
@@ -517,8 +541,22 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe
517541 funcName = ( name + key + subKey ) . replace ( / [ - . \[ \] ] / g, '' ) // eslint-disable-line
518542 laterCode = buildArray ( schema , laterCode , funcName , externalSchema , fullSchema )
519543 code += `
520- json += ${ funcName } (obj${ accessor } )
521- `
544+ json += ${ funcName } (obj${ accessor } )
545+ `
546+ break
547+
548+ case undefined :
549+ if ( 'anyOf' in schema ) {
550+ schema . anyOf . forEach ( ( s , index ) => {
551+ code += `
552+ ${ index === 0 ? 'if' : 'else if' } (ajv.validate(${ require ( 'util' ) . inspect ( s , { depth : null } ) } , obj${ accessor } ))
553+ ${ nested ( laterCode , name , key , s , externalSchema , fullSchema , subKey ) . code }
554+ `
555+ } )
556+ code += `
557+ else json+= null
558+ `
559+ } else throw new Error ( `${ schema } unsupported` )
522560 break
523561 default :
524562 throw new Error ( `${ type } unsupported` )
0 commit comments