| 41 | * circular references |
| 42 | */ |
| 43 | export function jsonToSchemaObject( |
| 44 | json: JsonSchema, |
| 45 | visited: Map<JsonSchema, SchemaObject | SchemaRef> = new Map(), |
| 46 | ): SchemaObject | SchemaRef { |
| 47 | // A flag to check if a schema object is fully converted |
| 48 | const converted = 'x-loopback-converted'; |
| 49 | const schema = visited.get(json); |
| 50 | if (schema != null && isSchemaObject(schema) && schema[converted] === false) { |
| 51 | return {$ref: `#/components/schemas/${json.title}`}; |
| 52 | } |
| 53 | if (schema != null) return schema; |
| 54 | |
| 55 | const result: SchemaObject = { |
| 56 | [converted]: false, |
| 57 | }; |
| 58 | visited.set(json, result); |
| 59 | const propsToIgnore = ['additionalItems', 'defaultProperties', 'typeof']; |
| 60 | for (const property in json) { |
| 61 | if (propsToIgnore.includes(property)) { |
| 62 | continue; |
| 63 | } |
| 64 | switch (property) { |
| 65 | case 'type': { |
| 66 | if (json.type === 'array' && !json.items) { |
| 67 | throw new Error( |
| 68 | '"items" property must be present if "type" is an array', |
| 69 | ); |
| 70 | } |
| 71 | result.type = Array.isArray(json.type) ? json.type[0] : json.type; |
| 72 | break; |
| 73 | } |
| 74 | case 'allOf': { |
| 75 | result.allOf = _.map(json.allOf, item => |
| 76 | jsonToSchemaObject(item as JsonSchema, visited), |
| 77 | ); |
| 78 | break; |
| 79 | } |
| 80 | case 'anyOf': { |
| 81 | result.anyOf = _.map(json.anyOf, item => |
| 82 | jsonToSchemaObject(item as JsonSchema, visited), |
| 83 | ); |
| 84 | break; |
| 85 | } |
| 86 | case 'oneOf': { |
| 87 | result.oneOf = _.map(json.oneOf, item => |
| 88 | jsonToSchemaObject(item as JsonSchema, visited), |
| 89 | ); |
| 90 | break; |
| 91 | } |
| 92 | case 'definitions': { |
| 93 | result.definitions = _.mapValues(json.definitions, def => |
| 94 | jsonToSchemaObject(jsonOrBooleanToJSON(def), visited), |
| 95 | ); |
| 96 | break; |
| 97 | } |
| 98 | case 'properties': { |
| 99 | result.properties = _.mapValues(json.properties, item => |
| 100 | jsonToSchemaObject(jsonOrBooleanToJSON(item), visited), |