@tsed/schema
Version:
JsonSchema module for Ts.ED Framework
75 lines (74 loc) • 3.07 kB
JavaScript
import { JsonSchema } from "../../domain/JsonSchema.js";
import { execMapper, registerJsonSchemaMapper } from "../../registries/JsonSchemaMapperContainer.js";
import { getGenericsOptions } from "../../utils/generics.js";
import { mergeSchema } from "../../utils/mergeSchema.js";
function getMapper(input, mapper, root) {
if (input.isClass && !input.isLocalSchema && !root) {
return mapper || "class";
}
return "any";
}
function buildAndMergeSchemas(mapper, schema1, schema2, options) {
const schema = execMapper(getMapper(schema2, mapper, options.root), [schema2], {
...options,
root: false,
mapper: mapper === "next" ? options.mapper : undefined
});
let extraSchema = execMapper(options.root ? "any" : mapper, [schema1], {
...options,
root: false,
generics: undefined,
mapper: mapper === "next" ? options.mapper : undefined
});
if ((schema.$ref || schema.allOf) && extraSchema.type && Object.keys(extraSchema).length === 1) {
extraSchema = {};
}
if (schema1.canRef) {
const name = extraSchema.$ref.split("/").pop();
const titleSchema = options.components.schemas[name];
options.components.schemas[name] = mergeSchema(schema, titleSchema);
return extraSchema;
}
return mergeSchema(schema, extraSchema);
}
export function itemMapper(input, options) {
if (input && input instanceof JsonSchema) {
if (!input.isCollection && input?.itemSchema?.()) {
const { generics, mapper } = getGenericsOptions(input, options);
const schema1 = input;
const schema2 = input.itemSchema();
return buildAndMergeSchemas("next", schema1, schema2, { ...options, generics, mapper });
}
}
return execMapper("next", [input], options);
}
export function nextMapper(input, options) {
if (input && input instanceof JsonSchema && !input.isLocalSchema) {
const refSchema = input.getRefSchema();
if (refSchema) {
let { generics, mapper } = getGenericsOptions(input, options);
mapper = getMapper(input, mapper);
return buildAndMergeSchemas(mapper, input, refSchema, {
...options,
generics
});
}
}
return execMapper(getMapper(input, options.mapper), [input], {
...options,
root: false,
mapper: undefined
});
}
registerJsonSchemaMapper("item", itemMapper);
registerJsonSchemaMapper("next", nextMapper);
registerJsonSchemaMapper("properties", nextMapper);
registerJsonSchemaMapper("items", nextMapper);
registerJsonSchemaMapper("additionalProperties", nextMapper);
registerJsonSchemaMapper("propertyNames", nextMapper);
registerJsonSchemaMapper("contains", nextMapper);
registerJsonSchemaMapper("dependencies", nextMapper);
registerJsonSchemaMapper("patternProperties", nextMapper);
registerJsonSchemaMapper("additionalItems", nextMapper);
registerJsonSchemaMapper("not", nextMapper);
registerJsonSchemaMapper("definitions", nextMapper);