MCPcopy Index your code
hub / github.com/fastify/fast-json-stringify / buildInnerObject

Function buildInnerObject

index.js:356–488  ·  view source on GitHub ↗
(context, location, objVar)

Source from the content-addressed store, hash-verified

354}
355
356function buildInnerObject (context, location, objVar) {
357 const schema = location.schema
358
359 const propertiesLocation = location.getPropertyLocation('properties')
360 const requiredProperties = schema.required || []
361
362 // Should serialize required properties first
363 const propertiesKeys = Object.keys(schema.properties || {}).sort(
364 (key1, key2) => {
365 const required1 = requiredProperties.includes(key1)
366 const required2 = requiredProperties.includes(key2)
367 return required1 === required2 ? 0 : required1 ? -1 : 1
368 }
369 )
370
371 let code = ''
372
373 for (const key of requiredProperties) {
374 if (!propertiesKeys.includes(key)) {
375 const sanitizedKey = JSON.stringify(key)
376 code += `if (${objVar}[${sanitizedKey}] === undefined) throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')\n`
377 }
378 }
379
380 code += 'json += JSON_STR_BEGIN_OBJECT\n'
381
382 const localUid = context.uid++
383 let addComma = ''
384
385 if (requiredProperties.length > 0) {
386 // If we have required properties, we know that at least one property will be serialized.
387 // We can avoid the runtime check for the comma.
388
389 // The first property is required, so we don't need a comma.
390 // For the subsequent properties, we can blindly add a comma.
391
392 for (let i = 0; i < propertiesKeys.length; i++) {
393 const key = propertiesKeys[i]
394 const propertyLocation = propertiesLocation.getPropertyLocation(key)
395
396 let resolvedLocation = propertyLocation
397 if (propertyLocation.schema.$ref) {
398 resolvedLocation = resolveRef(context, propertyLocation)
399 }
400
401 const sanitizedKey = JSON.stringify(key)
402 const value = `value_${key.replace(/[^a-zA-Z0-9]/g, '_')}_${context.uid++}`
403 const defaultValue = resolvedLocation.schema.default
404 const isRequired = requiredProperties.includes(key)
405
406 // i === 0 means it's the first property, and it IS required (due to sort). No comma.
407 // i > 0 means it follows a required property (or a sequence starting with one). Unconditional comma.
408 const currentAddComma = i === 0 ? '' : 'json += JSON_STR_COMMA'
409
410 code += `
411 const ${value} = ${objVar}[${sanitizedKey}]
412 if (${value} !== undefined) {
413 ${currentAddComma}

Callers 1

buildObjectFunction · 0.85

Calls 4

resolveRefFunction · 0.85
buildValueFunction · 0.85
getPropertyLocationMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…