nope/lib/helpers/jsonSchemaMethods.ts
Martin Karkowski d325c07c6c Fixing Open-Api Creation.
Provinding Swagger UI.
2020-08-25 10:21:55 +02:00

55 lines
1.4 KiB
TypeScript

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<string, any>) => {
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, '/');
}