安装依赖

1
pnpm add @nestjs/swagger swagger-ui-express

配置

main.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Response } from './common/response'
import { HttpFilter } from './common/filter'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'

async function bootstrap() {
const app = await NestFactory.create(AppModule)
// 设置全局前缀
app.setGlobalPrefix('api/v1')
// 生成文档
const options = new DocumentBuilder()
.setTitle('Nestjs API 接口文档') // 文档标题
.setDescription('Nestjs API 学习文档') // 文档描述
.setVersion('1.0') // 文档版本
.addBearerAuth() // 添加认证
.setBasePath('api/v1') // 设置基础路径
.build() // 生成文档配置
// 创建 Swagger 文档
const document = SwaggerModule.createDocument(app, options)
// 挂载 Swagger 文档到 /api-docs 路由
SwaggerModule.setup('/api-docs', app, document)
// 响应拦截器
app.useGlobalInterceptors(new Response())
// 错误过滤器
app.useGlobalFilters(new HttpFilter())
await app.listen(process.env.APP_PORT);
}
bootstrap();

create-user.dto.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { ApiProperty } from "@nestjs/swagger";

export class CreateUserDto {
id?: number;
@ApiProperty({
description: '用户名',
default: '王二',
type: String
})
username: string;
@ApiProperty({
description: '密码',
default: '123456',
type: String
})
password: string;
@ApiProperty({
description: '年龄',
default: 18,
type: Number
})
age: number;
}

user.controller.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { Controller, Get, Post, Body, Patch, Param, Delete, HttpStatus, HttpException } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';

@Controller('user')
@ApiTags('用户') // 标记路由
export class UserController {
constructor(private readonly userService: UserService) { }

@Post()
@ApiOperation({ summary: '创建用户' })
create(@Body() createUserDto: CreateUserDto) {
return this.userService.create(createUserDto);
}

@Get()
@ApiOperation({ summary: '查询所有用户' })
findAll() {
const a = process.env.SALT
return this.userService.findAll();
}

@Get(':id')
@ApiOperation({ summary: '根据id查询用户' })
findOne(@Param('id') id: string) {
// 根据id查询用户
const user = this.userService.findOne(+id)
if (!user) {
throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
} else {
return user
}
}

@Patch(':id')
@ApiOperation({ summary: '根据id更新用户' })
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.userService.update(+id, updateUserDto);
}

@Delete(':id')
@ApiOperation({ summary: '根据id删除用户' })
remove(@Param('id') id: string) {
return this.userService.remove(+id);
}
}