oa_based/src/setup-swagger.ts

44 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-02-28 17:02:46 +08:00
import { INestApplication, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
import { API_SECURITY_AUTH } from './common/decorators/swagger.decorator';
import { CommonEntity } from './common/entity/common.entity';
import { ResOp, TreeResult } from './common/model/response.model';
import { ConfigKeyPaths, IAppConfig, ISwaggerConfig } from './config';
import { Pagination } from './helper/paginate/pagination';
2024-02-28 08:32:35 +08:00
export function setupSwagger(
app: INestApplication,
2024-02-28 17:02:46 +08:00
configService: ConfigService<ConfigKeyPaths>
2024-02-28 08:32:35 +08:00
): void {
2024-02-28 17:02:46 +08:00
const { name, port } = configService.get<IAppConfig>('app')!;
const { enable, path } = configService.get<ISwaggerConfig>('swagger')!;
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
if (!enable) return;
2024-02-28 08:32:35 +08:00
const documentBuilder = new DocumentBuilder()
.setTitle(name)
.setDescription(`${name} API document`)
2024-02-28 17:02:46 +08:00
.setVersion('1.0');
2024-02-28 08:32:35 +08:00
// auth security
documentBuilder.addSecurity(API_SECURITY_AUTH, {
description: 'Auth',
type: 'apiKey',
in: 'header',
name: 'Authorization',
2024-02-28 17:02:46 +08:00
});
2024-02-28 08:32:35 +08:00
const document = SwaggerModule.createDocument(app, documentBuilder.build(), {
ignoreGlobalPrefix: false,
extraModels: [CommonEntity, ResOp, Pagination, TreeResult],
2024-02-28 17:02:46 +08:00
});
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
SwaggerModule.setup(path, app, document);
2024-02-28 08:32:35 +08:00
// started log
2024-02-28 17:02:46 +08:00
const logger = new Logger('SwaggerModule');
logger.log(`Document running on http://127.0.0.1:${port}/${path}`);
2024-02-28 08:32:35 +08:00
}