UNPKG

@tsed/schema

Version:
75 lines (74 loc) 2.06 kB
import { cleanObject, isArray } from "@tsed/core"; import { SpecTypes } from "../domain/SpecTypes.js"; import { execMapper } from "../registries/JsonSchemaMapperContainer.js"; import { getJsonEntityStore } from "./getJsonEntityStore.js"; import { mergeSpec } from "./mergeSpec.js"; import { operationIdFormatter } from "./operationIdFormatter.js"; /** * @ignore */ const caches = new Map(); /** * @ignore */ function get(model, options, cb) { if (!caches.has(model)) { caches.set(model, new Map()); } const cache = caches.get(model); const key = JSON.stringify(options); if (!cache.has(key)) { cache.set(key, cb()); } return cache.get(key); } function generate(model, options) { const store = getJsonEntityStore(model); const { rootPath = "/" } = options; options = { ...options, rootPath, defaultTags: [ cleanObject({ name: store.schema.getName(), description: store.schema.get("description") }) ] }; return execMapper("generate", [store], options); } /** * Return the swagger or open spec for the given class. * @param model * @param options */ export function getSpec(model, options = {}) { options = { specType: SpecTypes.OPENAPI, ...options, tags: [], paths: {}, channels: {}, components: {}, operationIdFormatter: options.operationIdFormatter || operationIdFormatter(options.operationIdPattern), root: false }; if (isArray(model)) { let finalSpec = {}; options = { ...options, append(spec) { finalSpec = mergeSpec(finalSpec, spec); } }; model.forEach(({ token, ...opts }) => { const spec = getSpec(token, { ...options, ...opts }); options.append(spec); }); return finalSpec; } return get(model, options, () => generate(model, options)); }