@@ -140,17 +140,33 @@ function buildObject (schema, code, name) {
140140 var laterCode = ''
141141
142142 Object . keys ( schema . properties ) . forEach ( ( key , i , a ) => {
143+ /* code += `
144+ if (obj.hasOwnProperty('${key}')) {
145+ json += '${$asString(key)}:'`*/
143146 code += `
144- json += ' ${ $asString ( key ) } :'
145- `
147+ if (obj. ${ key } !== undefined) {
148+ json += ' ${ $asString ( key ) } :' `
146149
147150 const result = nested ( laterCode , name , '.' + key , schema . properties [ key ] )
148151
149152 code += result . code
150153 laterCode = result . laterCode
151154
152155 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+ `
154170 }
155171 } )
156172
@@ -202,48 +218,36 @@ function buildArray (schema, code, name) {
202218function nested ( laterCode , name , key , schema ) {
203219 var code = ''
204220 var funcName
205- if ( schema . required ) {
206- code += `
207- if (!obj.hasOwnProperty('${ key . slice ( 1 ) } ')) {
208- throw new Error('${ key } is required!')
209- }`
210- }
211221 const type = schema . type
212222 switch ( type ) {
213223 case 'null' :
214224 code += `
215- json += $asNull()
216- `
225+ json += $asNull()`
217226 break
218227 case 'string' :
219228 code += `
220- json += $asString(obj${ key } )
221- `
229+ json += $asString(obj${ key } )`
222230 break
223231 case 'number' :
224232 case 'integer' :
225233 code += `
226- json += $asNumber(obj${ key } )
227- `
234+ json += $asNumber(obj${ key } )`
228235 break
229236 case 'boolean' :
230237 code += `
231- json += $asBoolean(obj${ key } )
232- `
238+ json += $asBoolean(obj${ key } )`
233239 break
234240 case 'object' :
235241 funcName = ( name + key ) . replace ( / [ - . \[ \] ] / g, '' )
236242 laterCode = buildObject ( schema , laterCode , funcName )
237243 code += `
238- json += ${ funcName } (obj${ key } )
239- `
244+ json += ${ funcName } (obj${ key } )`
240245 break
241246 case 'array' :
242247 funcName = ( name + key ) . replace ( / [ - . \[ \] ] / g, '' )
243248 laterCode = buildArray ( schema , laterCode , funcName )
244249 code += `
245- json += ${ funcName } (obj${ key } )
246- `
250+ json += ${ funcName } (obj${ key } )`
247251 break
248252 default :
249253 throw new Error ( `${ type } unsupported` )
0 commit comments