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.

310 lines (309 loc) • 14.2 kB
import { Logger, NotFoundException, RequestMethod } from '@nestjs/common'; import { loadPackage } from '@nestjs/common/utils/load-package.util.js'; import * as jsyaml from 'js-yaml'; import { posix } from 'path'; import { GLOBAL_PARAMETERS, GLOBAL_RESPONSES } from './interfaces/global-metadata.interface.js'; import { MetadataLoader } from './plugin/metadata-loader.js'; import { SwaggerScanner } from './swagger-scanner.js'; import { buildSwaggerHTML, buildSwaggerInitJS, getSwaggerAssetsAbsoluteFSPath } from './swagger-ui/index.js'; import { assignTwoLevelsDeep } from './utils/assign-two-levels-deep.js'; import { getGlobalPrefix } from './utils/get-global-prefix.js'; import { isOas31OrLater } from './utils/is-oas31-or-later.util.js'; import { isOas32OrLater } from './utils/is-oas32-or-later.util.js'; import { normalizeRelPath } from './utils/normalize-rel-path.js'; import { convertNullableToOas31 } from './utils/nullable-to-oas31.util.js'; import { removeDanglingLinks } from './utils/remove-dangling-links.util.js'; import { resolvePath } from './utils/resolve-path.util.js'; import { stripLastSlash } from './utils/strip-last-slash.util.js'; import { validateGlobalPrefix } from './utils/validate-global-prefix.util.js'; import { validatePath } from './utils/validate-path.util.js'; const isRoutePattern = (segment) => /[:*]/.test(segment); function isStockSwaggerUiFile(pathname) { let decodedPathname; try { decodedPathname = decodeURIComponent(pathname); } catch { return false; } const normalizedPathname = posix .normalize(`/${decodedPathname}`) .toLowerCase(); return (normalizedPathname === '/index.html' || normalizedPathname === '/license'); } const FIXED_PATH_ITEM_METHODS = [ 'get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace' ]; const NON_STANDARD_HTTP_METHODS = new Set(Object.values(RequestMethod) .filter((method) => typeof method === 'string') .map((method) => method.toLowerCase()) .filter((method) => method !== 'all' && !FIXED_PATH_ITEM_METHODS.includes(method))); export class SwaggerModule { static mergeWebhooks(configWebhooks, scannedWebhooks) { if (!configWebhooks && !scannedWebhooks) { return undefined; } return assignTwoLevelsDeep({}, configWebhooks || {}, scannedWebhooks || {}); } static normalizeNonStandardOperations(pathItems, isOas32) { const isNonStandard = (field) => NON_STANDARD_HTTP_METHODS.has(field) && !(isOas32 && field === 'query'); const result = {}; for (const [key, pathItem] of Object.entries(pathItems)) { if (!pathItem || !Object.keys(pathItem).some(isNonStandard)) { result[key] = pathItem; continue; } const rest = {}; const additionalOperations = { ...pathItem.additionalOperations }; for (const [field, value] of Object.entries(pathItem)) { if (!isNonStandard(field)) { rest[field] = value; } else if (isOas32) { additionalOperations[field.toUpperCase()] = value; } } if (isOas32) { rest.additionalOperations = additionalOperations; } if (Object.keys(rest).length > 0) { result[key] = rest; } } return result; } static createDocument(app, config, options = {}) { const { webhooks: configWebhooks, [GLOBAL_PARAMETERS]: globalParameters, [GLOBAL_RESPONSES]: globalResponses, ...configWithoutWebhooks } = config; const swaggerScanner = new SwaggerScanner(); const document = swaggerScanner.scanApplication(app, options, { globalParameters, globalResponses }); document.components = assignTwoLevelsDeep({}, config.components, document.components); const { webhooks: scannedWebhooks, webhookPaths, ...documentWithoutWebhooks } = document; const mergedWebhooks = SwaggerModule.mergeWebhooks(configWebhooks, scannedWebhooks); const openApiVersion = config.openapi ?? '3.0.0'; const isOas31 = isOas31OrLater(openApiVersion); const baseDocument = { openapi: '3.0.0', paths: {}, ...configWithoutWebhooks, ...documentWithoutWebhooks }; if (!isOas31 && webhookPaths) { for (const [path, webhookPathItem] of Object.entries(webhookPaths)) { for (const method of Object.keys(webhookPathItem)) { if (baseDocument.paths?.[path]?.[method]) { new Logger(SwaggerModule.name).warn(`Webhook "${method.toUpperCase()} ${path}" shares its path and method with a route, so it is left out of the OpenAPI ${openApiVersion} document. Use OpenAPI 3.1 or later to document both.`); } } } } const finalDocument = isOas31 ? { ...baseDocument, ...(mergedWebhooks ? { webhooks: mergedWebhooks } : {}) } : { ...baseDocument, paths: webhookPaths ? assignTwoLevelsDeep({}, baseDocument.paths || {}, webhookPaths, baseDocument.paths || {}) : baseDocument.paths }; if (isOas31) { convertNullableToOas31(finalDocument); } const isOas32 = isOas32OrLater(openApiVersion); finalDocument.paths = SwaggerModule.normalizeNonStandardOperations(finalDocument.paths, isOas32); if (finalDocument.webhooks) { finalDocument.webhooks = SwaggerModule.normalizeNonStandardOperations(finalDocument.webhooks, isOas32); } removeDanglingLinks(finalDocument); return finalDocument; } static async loadPluginMetadata(metadataFn) { const metadata = await metadataFn(); return this.metadataLoader.load(metadata); } static serveStatic(finalPath, app, customStaticPath) { const httpAdapter = app.getHttpAdapter(); const swaggerAssetsPath = customStaticPath ? resolvePath(customStaticPath) : getSwaggerAssetsAbsoluteFSPath(); if (httpAdapter && httpAdapter.getType() === 'fastify') { httpAdapter.getInstance().register(async (instance) => { const fastifyStaticModule = await loadPackage('@fastify/static', 'SwaggerModule', () => import('@fastify/static')); const fastifyStatic = fastifyStaticModule.default ?? fastifyStaticModule; instance.register(fastifyStatic, { root: swaggerAssetsPath, prefix: finalPath, decorateReply: false, index: false, allowedPath: (pathname) => !isStockSwaggerUiFile(pathname) }); }); } else { app.use(finalPath, (req, res, next) => isStockSwaggerUiFile(req.path) ? next(new NotFoundException()) : next()); app.useStaticAssets(swaggerAssetsPath, { prefix: finalPath, index: false }); } } static serveDocuments(finalPath, urlLastSubdirectory, httpAdapter, documentOrFactory, options) { let document; const getBuiltDocument = () => { if (!document) { document = typeof documentOrFactory === 'function' ? documentOrFactory() : documentOrFactory; } return document; }; if (options.ui) { this.serveSwaggerUi(finalPath, urlLastSubdirectory, httpAdapter, getBuiltDocument, options.swaggerOptions); } if (options.raw === true || (Array.isArray(options.raw) && options.raw.length > 0)) { const serveJson = options.raw === true || options.raw.includes('json'); const serveYaml = options.raw === true || options.raw.includes('yaml'); this.serveDefinitions(httpAdapter, getBuiltDocument, options, { serveJson, serveYaml }); } } static serveSwaggerUi(finalPath, urlLastSubdirectory, httpAdapter, getBuiltDocument, swaggerOptions) { const baseUrlForSwaggerUI = normalizeRelPath(`./${urlLastSubdirectory}/`); let swaggerUiHtml; let swaggerUiHtmlForTrailingSlash; let swaggerUiInitJS; async function serveSwaggerInitJs(req, res) { res.type('application/javascript'); const document = getBuiltDocument(); if (swaggerOptions.patchDocumentOnRequest) { const documentToSerialize = await Promise.resolve(swaggerOptions.patchDocumentOnRequest(req, res, document)); const swaggerInitJsPerRequest = buildSwaggerInitJS(documentToSerialize, swaggerOptions); return res.send(swaggerInitJsPerRequest); } if (!swaggerUiInitJS) { swaggerUiInitJS = buildSwaggerInitJS(document, swaggerOptions); } return res.send(swaggerUiInitJS); } httpAdapter.get(normalizeRelPath(`${finalPath}/swagger-ui-init.js`), serveSwaggerInitJs); if (!isRoutePattern(urlLastSubdirectory)) { try { httpAdapter.get(normalizeRelPath(`${finalPath}/${urlLastSubdirectory}/swagger-ui-init.js`), serveSwaggerInitJs); } catch { } } const getSwaggerHtml = () => { if (!swaggerUiHtml) { swaggerUiHtml = buildSwaggerHTML(baseUrlForSwaggerUI, swaggerOptions); } return swaggerUiHtml; }; const getTrailingSlashSwaggerHtml = () => { if (!swaggerUiHtmlForTrailingSlash) { swaggerUiHtmlForTrailingSlash = buildSwaggerHTML('./', swaggerOptions); } return swaggerUiHtmlForTrailingSlash; }; function serveSwaggerHtml(req, res) { res.type('text/html'); const [pathname] = httpAdapter.getRequestUrl(req).split('?'); const isFolderUrl = pathname.endsWith('/') || pathname.endsWith('/index.html'); const swaggerUiHtml = isFolderUrl ? getTrailingSlashSwaggerHtml() : getSwaggerHtml(); res.send(swaggerUiHtml); } httpAdapter.get(finalPath, serveSwaggerHtml); httpAdapter.get(`${finalPath}/index.html`, serveSwaggerHtml); httpAdapter.get(`${finalPath}/LICENSE`, () => { throw new NotFoundException(); }); try { httpAdapter.get(normalizeRelPath(`${finalPath}/`), serveSwaggerHtml); } catch { } } static serveDefinitions(httpAdapter, getBuiltDocument, options, serveOptions) { if (serveOptions.serveJson) { httpAdapter.get(normalizeRelPath(options.jsonDocumentUrl), async (req, res) => { res.type('application/json'); const document = getBuiltDocument(); const documentToSerialize = options.swaggerOptions .patchDocumentOnRequest ? await Promise.resolve(options.swaggerOptions.patchDocumentOnRequest(req, res, document)) : document; return res.send(JSON.stringify(documentToSerialize)); }); } if (serveOptions.serveYaml) { httpAdapter.get(normalizeRelPath(options.yamlDocumentUrl), async (req, res) => { res.type('text/yaml'); const document = getBuiltDocument(); const documentToSerialize = options.swaggerOptions .patchDocumentOnRequest ? await Promise.resolve(options.swaggerOptions.patchDocumentOnRequest(req, res, document)) : document; const yamlDocument = jsyaml.dump(documentToSerialize, { skipInvalid: true, noRefs: true }); return res.send(yamlDocument); }); } } static setup(path, app, documentOrFactory, options) { const globalPrefix = stripLastSlash(getGlobalPrefix(app)); const finalPath = validatePath(options?.useGlobalPrefix && validateGlobalPrefix(globalPrefix) ? `${globalPrefix}${validatePath(path)}` : path); const urlLastSubdirectory = finalPath.split('/').slice(-1).pop() || ''; const validatedGlobalPrefix = options?.useGlobalPrefix && validateGlobalPrefix(globalPrefix) ? validatePath(globalPrefix) : ''; const finalJSONDocumentPath = options?.jsonDocumentUrl ? `${validatedGlobalPrefix}${validatePath(options.jsonDocumentUrl)}` : `${finalPath}-json`; const finalYAMLDocumentPath = options?.yamlDocumentUrl ? `${validatedGlobalPrefix}${validatePath(options.yamlDocumentUrl)}` : `${finalPath}-yaml`; const ui = options?.ui ?? options?.swaggerUiEnabled ?? true; const raw = options?.raw ?? true; const httpAdapter = app.getHttpAdapter(); SwaggerModule.serveDocuments(finalPath, urlLastSubdirectory, httpAdapter, documentOrFactory, { ui, raw, jsonDocumentUrl: finalJSONDocumentPath, yamlDocumentUrl: finalYAMLDocumentPath, swaggerOptions: options || {} }); if (ui) { SwaggerModule.serveStatic(finalPath, app, options?.customSwaggerUiPath); if (isRoutePattern(urlLastSubdirectory) || finalPath === `/${urlLastSubdirectory}`) { return; } const serveStaticSlashEndingPath = `${finalPath}/${urlLastSubdirectory}`; SwaggerModule.serveStatic(serveStaticSlashEndingPath, app, options?.customSwaggerUiPath); } } } SwaggerModule.metadataLoader = new MetadataLoader();