@@ -140,17 +140,33 @@ function buildObject (schema, code, name) {
140
140
var laterCode = ''
141
141
142
142
Object . keys ( schema . properties ) . forEach ( ( key , i , a ) => {
143
+ /* code += `
144
+ if (obj.hasOwnProperty('${key}')) {
145
+ json += '${$asString(key)}:'`*/
143
146
code += `
144
- json += ' ${ $asString ( key ) } :'
145
- `
147
+ if (obj. ${ key } !== undefined) {
148
+ json += ' ${ $asString ( key ) } :' `
146
149
147
150
const result = nested ( laterCode , name , '.' + key , schema . properties [ key ] )
148
151
149
152
code += result . code
150
153
laterCode = result . laterCode
151
154
152
155
if ( i < a . length - 1 ) {
153
- code += 'json += \',\''
156
+ code += `
157
+ json += \',\'`
158
+ }
159
+
160
+ if ( schema . properties [ key ] . required ) {
161
+ code += `
162
+ } else {
163
+ throw new Error('${ key } is required!')
164
+ }
165
+ `
166
+ } else {
167
+ code += `
168
+ }
169
+ `
154
170
}
155
171
} )
156
172
@@ -202,48 +218,36 @@ function buildArray (schema, code, name) {
202
218
function nested ( laterCode , name , key , schema ) {
203
219
var code = ''
204
220
var funcName
205
- if ( schema . required ) {
206
- code += `
207
- if (!obj.hasOwnProperty('${ key . slice ( 1 ) } ')) {
208
- throw new Error('${ key } is required!')
209
- }`
210
- }
211
221
const type = schema . type
212
222
switch ( type ) {
213
223
case 'null' :
214
224
code += `
215
- json += $asNull()
216
- `
225
+ json += $asNull()`
217
226
break
218
227
case 'string' :
219
228
code += `
220
- json += $asString(obj${ key } )
221
- `
229
+ json += $asString(obj${ key } )`
222
230
break
223
231
case 'number' :
224
232
case 'integer' :
225
233
code += `
226
- json += $asNumber(obj${ key } )
227
- `
234
+ json += $asNumber(obj${ key } )`
228
235
break
229
236
case 'boolean' :
230
237
code += `
231
- json += $asBoolean(obj${ key } )
232
- `
238
+ json += $asBoolean(obj${ key } )`
233
239
break
234
240
case 'object' :
235
241
funcName = ( name + key ) . replace ( / [ - . \[ \] ] / g, '' )
236
242
laterCode = buildObject ( schema , laterCode , funcName )
237
243
code += `
238
- json += ${ funcName } (obj${ key } )
239
- `
244
+ json += ${ funcName } (obj${ key } )`
240
245
break
241
246
case 'array' :
242
247
funcName = ( name + key ) . replace ( / [ - . \[ \] ] / g, '' )
243
248
laterCode = buildArray ( schema , laterCode , funcName )
244
249
code += `
245
- json += ${ funcName } (obj${ key } )
246
- `
250
+ json += ${ funcName } (obj${ key } )`
247
251
break
248
252
default :
249
253
throw new Error ( `${ type } unsupported` )
0 commit comments