nope-js-browser
Version:
NoPE Runtime for the Browser. For nodejs please use nope-js-node
93 lines (92 loc) • 3.21 kB
JavaScript
/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
*/
import { isJsonSchema } from "./jsonSchemaMethods";
import { SPLITCHAR } from "./objectMethods";
/**
* Helper, to parse a {@link INopeDescriptor} to a
* @param schema
* @param toJSONSchema
* @param workWithRefs
* @param definitions
* @returns
*/
export function parseFunctionToJsonSchema(schema, toJSONSchema = true, workWithRefs = true, definitions = {}, prePathInput = "input", prePathOutput = "output", splitChar = SPLITCHAR) {
if (schema.type === "function") {
const inputSchema = {
type: "object",
properties: {},
required: [],
definitions: {},
};
/**
* A Helper Function, to parse the Parameter
* @param schemaToStore
* @param name
* @param optional
* @param schema
* @param preString
*/
function parseParameter(schemaToStore, name, optional, schema, preString, isInput) {
if (toJSONSchema && !isJsonSchema(schema)) {
throw Error("Schema contains functions as paramter");
}
if (isInput)
order.push(name);
if (!optional) {
schemaToStore.required.push(name);
}
if (workWithRefs) {
const ref = preString ? preString + splitChar + name : name;
// store the id.
ids.push(ref);
// We only want to store the Reference.
schemaToStore.properties[name] = {
$ref: ref,
};
// Now store the element as Reference
schema["$id"] = ref;
definitions[ref] = schema;
}
else {
schemaToStore.properties[name] = schema;
}
}
const order = [];
const ids = [];
for (const input of schema.inputs || []) {
parseParameter(inputSchema, input.name, input.optional, input.schema, prePathInput, true);
}
// Now lets store the
definitions[prePathInput] = inputSchema;
if (Array.isArray(schema.outputs)) {
const outputSchema = {
type: "object",
properties: {},
required: [],
definitions: {},
};
for (const output of schema.outputs) {
parseParameter(outputSchema, output.name, output.optional, output.schema, prePathOutput, false);
}
definitions[prePathInput] = outputSchema;
}
else if (schema.outputs) {
if (toJSONSchema && !isJsonSchema(schema.outputs)) {
throw Error("Output contains a Function => it can not be parsed");
}
definitions[prePathOutput] = schema.outputs;
}
return {
definitions,
order,
ids,
inputId: prePathInput,
outputId: prePathOutput,
};
}
else {
throw Error("Expecting a function");
}
}