你瞅啥呢

2025-11-26 给nestJS项目增加Swagger接口文档(deepseek)

NestJS 项目集成 Swagger 接口文档指南

1. 安装依赖

npm install @nestjs/swagger swagger-ui-express

2. 基础配置

main.ts 文件中进行基础配置:

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);

// Swagger 配置
const config = new DocumentBuilder()
.setTitle('API 文档')
.setDescription('NestJS API 接口文档')
.setVersion('1.0')
.addTag('users', '用户相关接口')
.addTag('auth', '认证相关接口')
.addBearerAuth() // 添加 JWT 认证
.build();

const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document, {
swaggerOptions: {
persistAuthorization: true, // 保持认证状态
},
});

await app.listen(3000);
}
bootstrap();

3. DTO 配置

为 DTO 添加 Swagger 装饰器:

import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsString, IsEmail, IsOptional, MinLength } from 'class-validator';

export class CreateUserDto {
@ApiProperty({ description: '用户名', example: 'john_doe' })
@IsString()
@MinLength(3)
username: string;

@ApiProperty({ description: '邮箱地址', example: 'john@example.com' })
@IsEmail()
email: string;

@ApiProperty({ description: '密码', example: 'password123' })
@IsString()
@MinLength(6)
password: string;

@ApiPropertyOptional({ description: '手机号码', example: '13800138000' })
@IsOptional()
@IsString()
phone?: string;
}

export class LoginDto {
@ApiProperty({ description: '用户名或邮箱', example: 'john_doe' })
@IsString()
identifier: string;

@ApiProperty({ description: '密码', example: 'password123' })
@IsString()
password: string;
}

4. Controller 配置

为控制器添加 Swagger 装饰器:

import { Controller, Get, Post, Body, Param, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBearerAuth } from '@nestjs/swagger';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';

@ApiTags('users')
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}

@Post()
@ApiOperation({ summary: '创建用户', description: '创建新用户账号' })
@ApiResponse({ status: 201, description: '用户创建成功' })
@ApiResponse({ status: 400, description: '请求参数错误' })
@ApiResponse({ status: 409, description: '用户名或邮箱已存在' })
async create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}

@Get()
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '获取所有用户', description: '获取用户列表(需要认证)' })
@ApiResponse({ status: 200, description: '获取成功' })
async findAll() {
return this.usersService.findAll();
}

@Get(':id')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '获取用户详情' })
@ApiParam({ name: 'id', description: '用户ID', example: 1 })
@ApiResponse({ status: 200, description: '获取成功' })
@ApiResponse({ status: 404, description: '用户不存在' })
async findOne(@Param('id') id: string) {
return this.usersService.findOne(+id);
}
}

5. 认证配置

认证相关接口配置:

import { Controller, Post, Body } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';

@ApiTags('auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}

@Post('login')
@ApiOperation({ summary: '用户登录' })
@ApiResponse({
status: 200,
description: '登录成功',
schema: {
example: {
access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
expires_in: 3600
}
}
})
@ApiResponse({ status: 401, description: '认证失败' })
async login(@Body() loginDto: LoginDto) {
return this.authService.login(loginDto);
}
}

6. 高级配置

创建独立的 Swagger 配置文件:

// swagger.config.ts
import { DocumentBuilder, SwaggerCustomOptions } from '@nestjs/swagger';

export const swaggerConfig = new DocumentBuilder()
.setTitle('NestJS API')
.setDescription('NestJS 项目 API 接口文档')
.setVersion('1.0')
.addBearerAuth(
{
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
name: 'JWT',
description: '输入 JWT token',
in: 'header',
},
'JWT-auth',
)
.addTag('users', '用户管理')
.addTag('auth', '认证授权')
.build();

export const swaggerCustomOptions: SwaggerCustomOptions = {
swaggerOptions: {
persistAuthorization: true,
docExpansion: 'none',
filter: true,
showRequestDuration: true,
},
customSiteTitle: 'NestJS API Docs',
};

main.ts 中使用高级配置:

import { swaggerConfig, swaggerCustomOptions } from './swagger.config';

const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('docs', app, document, swaggerCustomOptions);

7. 实体类配置

为 TypeORM 实体添加 Swagger 装饰器:

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';

@Entity()
export class User {
@PrimaryGeneratedColumn()
@ApiProperty({ description: '用户ID', example: 1 })
id: number;

@Column()
@ApiProperty({ description: '用户名', example: 'john_doe' })
username: string;

@Column()
@ApiProperty({ description: '邮箱地址', example: 'john@example.com' })
email: string;

@Column({ select: false })
password: string;

@Column({ default: true })
@ApiProperty({ description: '是否激活', example: true })
isActive: boolean;

@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
@ApiProperty({ description: '创建时间', example: '2023-01-01T00:00:00.000Z' })
createdAt: Date;
}

8. 访问文档

启动项目后访问:

http://localhost:3000/api

或自定义路径:

http://localhost:3000/docs

9. 常用装饰器参考

装饰器 用途
@ApiTags('标签') 控制器分组
@ApiOperation() 接口描述
@ApiProperty() DTO 属性描述
@ApiResponse() 定义响应
@ApiParam() 路径参数描述
@ApiQuery() 查询参数描述
@ApiBearerAuth() Bearer 认证
@ApiBody() 请求体描述

10. 插件支持(可选)

安装开发依赖:

npm install --save-dev @nestjs/swagger-plugin

配置 nest-cli.json

{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"plugins": ["@nestjs/swagger/plugin"]
}
}

完成以上配置后,你的 NestJS 项目就成功集成了 Swagger 接口文档,可以通过 Swagger UI 测试所有 API 接口。

posted @ 2025-11-26 15:58  叶乘风  阅读(24)  评论(0)    收藏  举报