(schema, config = { })
| 475 | |
| 476 | /* For changing JSON-Schema to a Sample Object, as per the schema (to generate examples based on schema) */ |
| 477 | export function schemaToSampleObj(schema, config = { }) { |
| 478 | let obj = {}; |
| 479 | if (!schema) { |
| 480 | return; |
| 481 | } |
| 482 | if (schema.allOf) { |
| 483 | const objWithAllProps = {}; |
| 484 | |
| 485 | if (schema.allOf.length === 1 && !schema.allOf[0]?.properties && !schema.allOf[0]?.items) { |
| 486 | // If allOf has single item and the type is not an object or array, then its a primitive |
| 487 | if (schema.allOf[0].$ref) { |
| 488 | return '{ }'; |
| 489 | } |
| 490 | if (schema.allOf[0].readOnly && config.includeReadOnly) { |
| 491 | const tempSchema = schema.allOf[0]; |
| 492 | return getSampleValueByType(tempSchema); |
| 493 | } |
| 494 | return; |
| 495 | } |
| 496 | |
| 497 | schema.allOf.forEach((v) => { |
| 498 | if (v.type === 'object' || v.properties || v.allOf || v.anyOf || v.oneOf) { |
| 499 | const partialObj = schemaToSampleObj(v, config); |
| 500 | Object.assign(objWithAllProps, partialObj); |
| 501 | } else if (v.type === 'array' || v.items) { |
| 502 | const partialObj = [schemaToSampleObj(v, config)]; |
| 503 | Object.assign(objWithAllProps, partialObj); |
| 504 | } else if (v.type) { |
| 505 | const prop = `prop${Object.keys(objWithAllProps).length}`; |
| 506 | objWithAllProps[prop] = getSampleValueByType(v); |
| 507 | } else { |
| 508 | return ''; |
| 509 | } |
| 510 | }); |
| 511 | |
| 512 | obj = objWithAllProps; |
| 513 | } else if (schema.oneOf) { |
| 514 | // 1. First create example with scheme.properties |
| 515 | const objWithSchemaProps = {}; |
| 516 | if (schema.properties) { |
| 517 | for (const propertyName in schema.properties) { |
| 518 | if (schema.properties[propertyName].properties || schema.properties[propertyName].properties?.items) { |
| 519 | objWithSchemaProps[propertyName] = schemaToSampleObj(schema.properties[propertyName], config); |
| 520 | } else { |
| 521 | objWithSchemaProps[propertyName] = getSampleValueByType(schema.properties[propertyName]); |
| 522 | } |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | if (schema.oneOf.length > 0) { |
| 527 | /* |
| 528 | oneOf: |
| 529 | - type: object |
| 530 | properties: |
| 531 | option1_PropA: |
| 532 | type: string |
| 533 | option1_PropB: |
| 534 | type: string |
no test coverage detected
searching dependent graphs…