From ac92dcc67bad3d28d404bce1de90f9a4c4779bc1 Mon Sep 17 00:00:00 2001 From: moyin <244344649@qq.com> Date: Wed, 17 Dec 2025 15:15:14 +0800 Subject: [PATCH] =?UTF-8?q?config=EF=BC=9A=E9=85=8D=E7=BD=AESwagger=20API?= =?UTF-8?q?=E6=96=87=E6=A1=A3=E7=B3=BB=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在main.ts中集成Swagger UI - 配置API文档基本信息和JWT认证 - 设置文档访问路径为/api-docs --- src/main.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/main.ts b/src/main.ts index 1ea34d4..4f1028d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,9 +1,11 @@ import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ValidationPipe } from '@nestjs/common'; +import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; async function bootstrap() { const app = await NestFactory.create(AppModule); + // 全局启用校验管道(核心配置) app.useGlobalPipes( new ValidationPipe({ @@ -12,8 +14,36 @@ async function bootstrap() { transform: true, // 自动把入参转为 DTO 对应的类型(比如前端传的字符串数字 `'1'` 转为数字 `1`) }), ); + + // 配置Swagger文档 + const config = new DocumentBuilder() + .setTitle('Pixel Game Server API') + .setDescription('像素游戏服务器API文档 - 包含用户认证、登录注册等功能') + .setVersion('1.0.0') + .addTag('auth', '用户认证相关接口') + .addBearerAuth( + { + type: 'http', + scheme: 'bearer', + bearerFormat: 'JWT', + name: 'JWT', + description: '请输入JWT token', + in: 'header', + }, + 'JWT-auth', + ) + .build(); + + const document = SwaggerModule.createDocument(app, config); + SwaggerModule.setup('api-docs', app, document, { + swaggerOptions: { + persistAuthorization: true, + }, + }); + await app.listen(3000); console.log('Pixel Game Server is running on http://localhost:3000'); + console.log('API Documentation is available at http://localhost:3000/api-docs'); } bootstrap();