62 lines
1.6 KiB
TypeScript
62 lines
1.6 KiB
TypeScript
/**
|
|
* @author Martin Karkowski
|
|
* @email m.karkowski@zema.de
|
|
* @create date 2020-11-06 08:53:55
|
|
* @modify date 2020-11-06 08:53:56
|
|
* @desc [description]
|
|
*/
|
|
|
|
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 as IJsonSchema;
|
|
}
|
|
|
|
/**
|
|
* 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, "/");
|
|
}
|