nope/lib/helpers/jsonSchemaMethods.ts
2020-11-05 18:02:29 +01:00

55 lines
1.5 KiB
TypeScript

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);
}
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, '/');
}