UNPKG

@tsed/schema

Version:
72 lines (71 loc) 2.52 kB
import { isObject } from "@tsed/core"; import { VendorKeys } from "../../constants/VendorKeys.js"; import { JsonSchema } from "../../domain/JsonSchema.js"; import { execMapper, registerJsonSchemaMapper } from "../../registries/JsonSchemaMapperContainer.js"; import { toRef } from "../../utils/ref.js"; function getNestedSchema(propertyKey, schema, options) { if ("isLazyRef" in schema) { return null; } if (schema.isGeneric) { const genericLabel = schema.get(VendorKeys.GENERIC_LABEL); const genericValue = options.generics?.[genericLabel]; if (!genericValue) { return null; } const [model, next] = genericValue; const refSchema = JsonSchema.from(model); const modelSchema = execMapper("schema", [refSchema], { ...options, generics: next }); if (next || !refSchema.isClass) { return modelSchema; } return toRef(refSchema, modelSchema, options); } if (schema?.has("items")) { const nestedSchema = getNestedSchema(propertyKey, schema.get("items"), options); if (nestedSchema) { return { type: "array", items: nestedSchema }; } } if (schema.has("additionalProperties") && isObject(schema.get("additionalProperties"))) { const nestedSchema = getNestedSchema(propertyKey, schema.get("additionalProperties"), options); if (nestedSchema) { return { type: "object", additionalProperties: nestedSchema }; } } return null; } /** * @ignore */ export function genericsMapper(baseObj, schema, options) { if (schema.genericLabels?.length && schema.has("properties")) { const properties = schema.get("properties"); let hasProps = false; const additionalObj = Object.entries(properties || {}).reduce((obj, [propertyKey, jsonSchema]) => { const nestedSchema = getNestedSchema(propertyKey, jsonSchema, options); if (nestedSchema) { obj[propertyKey] = nestedSchema; hasProps = true; } return obj; }, {}); if (hasProps) { return { allOf: [toRef(schema, baseObj, options), { properties: additionalObj, type: "object" }] }; } return baseObj; } return baseObj; } registerJsonSchemaMapper("generics", genericsMapper);