@@ -62,6 +62,10 @@ function build (schema, options) {
62
62
`
63
63
}
64
64
65
+ if ( schema . type === undefined ) {
66
+ schema . type = inferTypeByKeyword ( schema )
67
+ }
68
+
65
69
var hasSchemaSomeIf = hasIf ( schema )
66
70
67
71
var main
@@ -114,6 +118,59 @@ function build (schema, options) {
114
118
return ( Function . apply ( null , dependenciesName ) . apply ( null , dependencies ) )
115
119
}
116
120
121
+ const objectKeywords = [
122
+ 'maxProperties' ,
123
+ 'minProperties' ,
124
+ 'required' ,
125
+ 'properties' ,
126
+ 'patternProperties' ,
127
+ 'additionalProperties' ,
128
+ 'dependencies'
129
+ ]
130
+
131
+ const arrayKeywords = [
132
+ 'items' ,
133
+ 'additionalItems' ,
134
+ 'maxItems' ,
135
+ 'minItems' ,
136
+ 'uniqueItems' ,
137
+ 'contains'
138
+ ]
139
+
140
+ const stringKeywords = [
141
+ 'maxLength' ,
142
+ 'minLength' ,
143
+ 'pattern'
144
+ ]
145
+
146
+ const numberKeywords = [
147
+ 'multipleOf' ,
148
+ 'maximum' ,
149
+ 'exclusiveMaximum' ,
150
+ 'minimum' ,
151
+ 'exclusiveMinimum'
152
+ ]
153
+
154
+ /**
155
+ * Infer type based on keyword in order to generate optimized code
156
+ * https://json-schema.org/latest/json-schema-validation.html#rfc.section.6
157
+ */
158
+ function inferTypeByKeyword ( schema ) {
159
+ for ( const keyword of objectKeywords ) {
160
+ if ( keyword in schema ) return 'object'
161
+ }
162
+ for ( const keyword of arrayKeywords ) {
163
+ if ( keyword in schema ) return 'array'
164
+ }
165
+ for ( const keyword of stringKeywords ) {
166
+ if ( keyword in schema ) return 'string'
167
+ }
168
+ for ( const keyword of numberKeywords ) {
169
+ if ( keyword in schema ) return 'number'
170
+ }
171
+ return schema . type
172
+ }
173
+
117
174
function hasAnyOf ( schema ) {
118
175
if ( 'anyOf' in schema ) { return true }
119
176
@@ -694,7 +751,16 @@ function buildArrayTypeCondition (type, accessor) {
694
751
function nested ( laterCode , name , key , schema , externalSchema , fullSchema , subKey ) {
695
752
var code = ''
696
753
var funcName
754
+
755
+ if ( schema . type === undefined ) {
756
+ var inferedType = inferTypeByKeyword ( schema )
757
+ if ( inferedType ) {
758
+ schema . type = inferedType
759
+ }
760
+ }
761
+
697
762
var type = schema . type
763
+
698
764
var accessor = key . indexOf ( '[' ) === 0 ? key : `['${ key } ']`
699
765
switch ( type ) {
700
766
case 'null' :
@@ -754,7 +820,7 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe
754
820
json += JSON.stringify(obj${ accessor } )
755
821
`
756
822
} else {
757
- throw new Error ( `${ schema } unsupported` )
823
+ throw new Error ( `${ schema . type } unsupported` )
758
824
}
759
825
break
760
826
default :
0 commit comments