1
1
'use strict'
2
2
3
3
var fastSafeStringify = require ( 'fast-safe-stringify' )
4
+ var Ajv = require ( 'ajv' )
4
5
5
6
var uglify = null
6
7
var isLong
@@ -87,8 +88,18 @@ function build (schema, options) {
87
88
code = uglifyCode ( code )
88
89
}
89
90
91
+ var dependencies = [ ]
92
+ var dependenciesName = [ ]
90
93
if ( hasAdditionalPropertiesTrue ( schema ) ) {
91
- return ( new Function ( 'fastSafeStringify' , code ) ) ( fastSafeStringify )
94
+ dependencies . push ( fastSafeStringify )
95
+ dependenciesName . push ( 'fastSafeStringify' )
96
+ }
97
+ if ( hasAnyOf ( schema ) ) {
98
+ dependencies . push ( new Ajv ( ) )
99
+ dependenciesName . push ( 'ajv' )
100
+ }
101
+ if ( dependencies . length > 0 ) {
102
+ return ( new Function ( ...dependenciesName , code ) ) ( ...dependencies )
92
103
}
93
104
return ( new Function ( code ) ) ( )
94
105
}
@@ -107,6 +118,20 @@ function hasAdditionalPropertiesTrue (schema) {
107
118
return false
108
119
}
109
120
121
+ function hasAnyOf ( schema ) {
122
+ if ( 'anyOf' in schema ) { return true }
123
+
124
+ var objectKeys = Object . keys ( schema )
125
+ for ( var i = 0 ; i < objectKeys . length ; i ++ ) {
126
+ var value = schema [ objectKeys [ i ] ]
127
+ if ( typeof value === 'object' ) {
128
+ if ( hasAnyOf ( value ) ) { return true }
129
+ }
130
+ }
131
+
132
+ return false
133
+ }
134
+
110
135
function $asNull ( ) {
111
136
return 'null'
112
137
}
@@ -517,8 +542,22 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe
517
542
funcName = ( name + key + subKey ) . replace ( / [ - . \[ \] ] / g, '' ) // eslint-disable-line
518
543
laterCode = buildArray ( schema , laterCode , funcName , externalSchema , fullSchema )
519
544
code += `
520
- json += ${ funcName } (obj${ accessor } )
521
- `
545
+ json += ${ funcName } (obj${ accessor } )
546
+ `
547
+ break
548
+
549
+ case undefined :
550
+ if ( 'anyOf' in schema ) {
551
+ schema . anyOf . forEach ( ( s , index ) => {
552
+ code += `
553
+ ${ index === 0 ? 'if' : 'else if' } (ajv.validate(${ require ( 'util' ) . inspect ( s , { depth : null } ) } , obj${ accessor } ))
554
+ ${ nested ( laterCode , name , key , s , externalSchema , fullSchema , subKey ) . code }
555
+ `
556
+ } )
557
+ code += `
558
+ else json+= null
559
+ `
560
+ } else throw new Error ( `${ schema } unsupported` )
522
561
break
523
562
default :
524
563
throw new Error ( `${ type } unsupported` )
0 commit comments