@nestjs/swagger
Version:
OpenAPI for NestJS: generate the API document from controllers and decorators, serve Swagger UI, and derive request types with mapped types.
137 lines (136 loc) • 6.9 kB
JavaScript
import { MODULE_METADATA, MODULE_PATH } from '@nestjs/common/constants.js';
import flatten from 'es-toolkit/compat/flatten';
import isEmpty from 'es-toolkit/compat/isEmpty';
import { ModelPropertiesAccessor } from './services/model-properties-accessor.js';
import { SchemaObjectFactory } from './services/schema-object-factory.js';
import { SwaggerTypesMapper } from './services/swagger-types-mapper.js';
import { SwaggerExplorer } from './swagger-explorer.js';
import { SwaggerTransformer } from './swagger-transformer.js';
import { applyExampleMaxDepth } from './utils/apply-example-max-depth.util.js';
import { getGlobalPrefix } from './utils/get-global-prefix.js';
import { stripDynamicDefaults, stripDynamicOperationDefaults } from './utils/strip-dynamic-defaults.util.js';
import { stripLastSlash } from './utils/strip-last-slash.util.js';
export class SwaggerScanner {
constructor() {
this.transformer = new SwaggerTransformer();
this.modelPropertiesAccessor = new ModelPropertiesAccessor();
this.swaggerTypesMapper = new SwaggerTypesMapper();
this.schemaObjectFactory = new SchemaObjectFactory(this.modelPropertiesAccessor, this.swaggerTypesMapper);
}
scanApplication(app, options, globalMetadata = {}) {
const { deepScanRoutes, include: includedModules = [], extraModels = [], ignoreGlobalPrefix = false, operationIdFactory, linkNameFactory, autoTagControllers = true, onlyIncludeDecoratedEndpoints = false, excludeDynamicDefaults = false, exampleMaxDepth, standardSchemaConverter } = options;
this.schemaObjectFactory = new SchemaObjectFactory(this.modelPropertiesAccessor, this.swaggerTypesMapper, standardSchemaConverter);
const untypedApp = app;
const container = untypedApp.container;
const internalConfigRef = untypedApp.config;
const httpAdapterType = app.getHttpAdapter().getType();
this.initializeSwaggerExplorer(httpAdapterType, standardSchemaConverter, globalMetadata);
const modules = this.getModules(container.getModules(), includedModules);
const globalPrefix = !ignoreGlobalPrefix
? stripLastSlash(getGlobalPrefix(app))
: '';
const denormalizedPaths = modules.map((module) => {
const { controllers, metatype, imports } = module;
let result = [];
if (deepScanRoutes) {
const explicitGlobalTokens = this.getExplicitlyImportedGlobalModuleTokens(container, module);
Array.from(imports.values())
.filter((importedModule) => !importedModule.isGlobal ||
explicitGlobalTokens === undefined ||
explicitGlobalTokens.has(importedModule.token))
.forEach(({ metatype, controllers }) => {
const modulePath = this.getModulePathMetadata(container, metatype);
result = result.concat(this.scanModuleControllers(controllers, internalConfigRef, {
modulePath,
globalPrefix,
operationIdFactory,
linkNameFactory,
autoTagControllers,
onlyIncludeDecoratedEndpoints
}));
});
}
const modulePath = this.getModulePathMetadata(container, metatype);
return result.concat(this.scanModuleControllers(controllers, internalConfigRef, {
modulePath,
globalPrefix,
operationIdFactory,
linkNameFactory,
autoTagControllers,
onlyIncludeDecoratedEndpoints
}));
});
const routes = flatten(denormalizedPaths);
const schemas = this.explorer.getSchemas();
this.addExtraModels(schemas, extraModels);
if (excludeDynamicDefaults) {
stripDynamicDefaults(schemas);
for (const route of routes) {
stripDynamicOperationDefaults(route);
}
}
applyExampleMaxDepth(schemas, exampleMaxDepth);
return {
...this.transformer.normalizePaths(routes),
components: {
schemas: schemas
}
};
}
getExplicitlyImportedGlobalModuleTokens(container, module) {
const tokenFactory = container.getModuleTokenFactory();
const staticImports = Reflect.getMetadata(MODULE_METADATA.IMPORTS, module.metatype) || [];
const dynamicImports = container.getDynamicMetadataByToken(module.token, 'imports') || [];
const tokens = new Set();
for (const importedModule of [...staticImports, ...dynamicImports]) {
const token = this.getModuleToken(importedModule, tokenFactory);
if (token === undefined || !container.getModules().has(token)) {
return undefined;
}
tokens.add(token);
}
return tokens;
}
getModuleToken(moduleReference, tokenFactory) {
let reference = moduleReference;
if ('forwardRef' in reference &&
typeof reference.forwardRef === 'function') {
reference = reference.forwardRef();
}
if (!reference || reference instanceof Promise) {
return undefined;
}
if ('module' in reference) {
const { module: metatype, ...dynamicMetadata } = reference;
return tokenFactory.createForDynamic(metatype, dynamicMetadata, reference);
}
return tokenFactory.createForStatic(reference, reference);
}
scanModuleControllers(controller, applicationConfig, options) {
const denormalizedArray = [...controller.values()].map((ctrl) => this.explorer.exploreController(ctrl, applicationConfig, options));
return flatten(denormalizedArray);
}
getModules(modulesContainer, include) {
if (!include || isEmpty(include)) {
return [...modulesContainer.values()];
}
return [...modulesContainer.values()].filter(({ metatype }) => include.some((item) => item === metatype));
}
addExtraModels(schemas, extraModels) {
extraModels.forEach((item) => {
this.schemaObjectFactory.exploreModelSchema(item, schemas);
});
}
getModulePathMetadata(container, metatype) {
const modulesContainer = container.getModules();
const modulePath = Reflect.getMetadata(MODULE_PATH + modulesContainer.applicationId, metatype);
return modulePath ?? Reflect.getMetadata(MODULE_PATH, metatype);
}
initializeSwaggerExplorer(httpAdapterType, standardSchemaConverter, globalMetadata) {
this.explorer = new SwaggerExplorer(this.schemaObjectFactory, {
httpAdapterType,
standardSchemaConverter,
...globalMetadata
});
}
}