UNPKG

@nestjs/swagger

Version:

OpenAPI for NestJS: generate the API document from controllers and decorators, serve Swagger UI, and derive request types with mapped types.

43 lines (42 loc) • 2.27 kB
import groupBy from 'es-toolkit/compat/groupBy'; import isEqual from 'es-toolkit/compat/isEqual'; import keyBy from 'es-toolkit/compat/keyBy'; import mapValues from 'es-toolkit/compat/mapValues'; import omit from 'es-toolkit/compat/omit'; import uniqWith from 'es-toolkit/compat/uniqWith'; import { sortObjectLexicographically } from './utils/sort-object-lexicographically.js'; export class SwaggerTransformer { normalizePaths(denormalizedDoc) { const roots = denormalizedDoc.filter((doc) => Boolean(doc.root)); const webhookRoots = roots.filter(({ root }) => Boolean(root.isWebhook)); const pathRoots = roots.filter(({ root }) => !root.isWebhook); const groupedByPath = groupBy(pathRoots, ({ root }) => root.path); const paths = mapValues(groupedByPath, (routes) => this.normalizeOperations(routes)); const groupedByWebhookName = groupBy(webhookRoots, ({ root }) => root.webhookName || root.path); const webhooks = mapValues(groupedByWebhookName, (routes) => this.normalizeOperations(routes)); const groupedByWebhookPath = groupBy(webhookRoots, ({ root }) => root.path); const webhookPaths = mapValues(groupedByWebhookPath, (routes) => this.normalizeOperations(routes)); return { paths, ...(Object.keys(webhooks).length > 0 ? { webhooks } : {}), ...(Object.keys(webhookPaths).length > 0 ? { webhookPaths } : {}) }; } normalizeOperations(routes) { const keyByMethod = keyBy(routes, ({ root }) => root.method); return mapValues(keyByMethod, (route) => { const mergedDefinition = { ...omit(route, 'root'), ...omit(route.root, ['method', 'path', 'isWebhook', 'webhookName']) }; const handlers = routes.filter(({ root }) => root.method === route.root.method); if (handlers.length > 1) { const security = uniqWith(handlers.flatMap((handler) => handler.root.security ?? handler.security ?? []), isEqual); if (security.length > 0) { mergedDefinition.security = security; } } return sortObjectLexicographically(mergedDefinition); }); } }