nope/lib/helpers/jsonSchemaMethods.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-11-06 08:10:30 +00:00
/**
* @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]
*/
2020-11-05 17:02:29 +00:00
import { IJsonSchema } from "../../resources/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);
}
2020-11-05 17:02:29 +00:00
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, '/');
}