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,10 +88,19 @@ 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' )
92
96
}
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 ) )
94
104
}
95
105
96
106
function hasAdditionalPropertiesTrue ( schema ) {
@@ -107,6 +117,20 @@ function hasAdditionalPropertiesTrue (schema) {
107
117
return false
108
118
}
109
119
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
+
110
134
function $asNull ( ) {
111
135
return 'null'
112
136
}
@@ -517,8 +541,22 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe
517
541
funcName = ( name + key + subKey ) . replace ( / [ - . \[ \] ] / g, '' ) // eslint-disable-line
518
542
laterCode = buildArray ( schema , laterCode , funcName , externalSchema , fullSchema )
519
543
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` )
522
560
break
523
561
default :
524
562
throw new Error ( `${ type } unsupported` )
0 commit comments