import { IJsonSchema } from "../../types/IJSONSchema"; import { flattenObject, rgetattr, rsetattr, SPLITCHAR } from "./objectMethods"; /** * Function to Flatten a JSON-Schema. * @param schema */ export function flattenSchema(schema: IJsonSchema) { let counter = 10000; let flattenSchema = flattenObject(schema); const getRefKeys = (flattenSchema: Map) => { const relevantKeys: Array<{ schemaPath: string, searchPath: string }> = [] for (const [key, value] of flattenSchema) { if (key.endsWith('$ref')) { relevantKeys.push({ schemaPath: key, searchPath: value.replace('#/', '').replace('/', SPLITCHAR) }) } } return relevantKeys; } let refs = getRefKeys(flattenSchema); while (refs.length > 0) { counter--; if (counter === 0) { throw Error('Max amount of Recursions performed') } for (const ref of refs) { const subSchema = rgetattr(schema, ref.searchPath, null, '.'); rsetattr(schema, ref.schemaPath.replace('.$ref', ''), subSchema) } flattenSchema = flattenObject(schema); refs = getRefKeys(flattenSchema); } return schema; } /** * Function to get a Schemas Definition * @param schema the JSON-Schema * @param reference the path of the relevant definition. */ export function schemaGetDefinition(schema: IJsonSchema, reference: string) { return rgetattr(schema, reference.replace('#/', ''), null, '/'); }