0x0 前言
OpenApi 规范是定义与 RESTful Api
的语言无关的标准接口,使用它不需要花大量的时间来编写接口文档。 Nest
提供一个模块,使系统支持此规范。
需要安装依赖如下:
yarn add @nestjs/swagger swagger-ui-express
0x1 初始化
在 main.ts
启用模块,使用 SwaggerModule
类来初始化 Swagger
:
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) const config = new DocumentBuilder() .setTitle('Vue Admin Plus 管理系统接口文档') .setDescription('这是一份关于 Vue Admin Plus 管理系统的接口文档') .setVersion('1.0.0') .build() const document = SwaggerModule.createDocument(app, config) SwaggerModule.setup('api', app, document) await app.listen(3000) } bootstrap().then()
然后可以访问 localhost:3000/api
即可看到 Swagger UI
文档。
0x2 类型和参数
SwaggerModule
搜索项目中所有可用的 @Body()
, @Query()
和 @Param()
装饰器来生成 Api
文档,同样可以利用反射来创建模型定义:
@Post() create(@Body() createUserDto: CreateUserDto): Promise<UserEntity> { return this.userService.create(createUserDto) }
上述代码会在 Swagger UI
生成模型,不过属性显示为空,需要添加注解才能支持:
import { ApiProperty } from '@nestjs/swagger' import { IsNotEmpty } from 'class-validator' export class CreateUserDto { @ApiProperty({ type: String, description: '用户账号' }) @IsNotEmpty() readonly username: string @ApiProperty({ type: String, description: '用户密码' }) @IsNotEmpty() readonly password: string @ApiProperty({ type: String, description: '用户邮箱' }) @IsNotEmpty() readonly email: string @ApiProperty({ type: String, description: '用户昵称' }) @IsNotEmpty() readonly nickname: string }
0x3 备注信息
默认文档渲染比较杂乱,可以利用 @ApiTags()
装饰器可以添加标签进行归纳:
@ApiTags('user') @Controller('user') export class UserController {}
如果需要自定义标头信息,可以用使用 @ApiHeader()
装饰器进行定义:
@ApiHeader({ name: 'X-MyHeader', description: 'Custom header', }) @Controller('user') export class UserController {}
如果需要自定义响应信息可以使用 @ApiResponse()
装饰器:
@Post() @ApiResponse({ status: 201, description: 'The record has been successfully created.'}) @ApiResponse({ status: 403, description: 'Forbidden.'}) async create(@Body() createUserDto: CreateUserDto) { this.userService.create(createCatDto) }
0x4 安全机制
对于特定的安全机制可以用 @ApiSecurity()
装饰器定义:
@ApiSecurity('basic') @Controller('cats') export class CatsController {}
然后在 main.ts
初始化的时候添加属性:
const options = new DocumentBuilder().addSecurity('basic', { type: 'http', scheme: 'basic' })
0x5 身份认证
对于身份验证需要 @ApiBasicAuth()
装饰器:
@ApiBasicAuth() @Controller('cats') export class CatsController {}
初始化添加属性:
const options = new DocumentBuilder().addBasicAuth()
0x6 承载认证
对于承载认证需要 @ApiBearerAuth()
装饰器:
@ApiBearerAuth() @Controller('cats') export class CatsController {}
初始化添加属性:
const options = new DocumentBuilder().addBearerAuth()
如果需要验证需要承载认证的接口,在 Swagger UI
的接口最右边小锁的图标点开,登录获取的 Token
字符串复制塞进去即可。
0x7 参考
注意:本文来自网友投稿。本站无法对本文内容的真实性、完整性、及时性、原创性提供任何保证,请您自行验证核实并承担相关的风险与后果!
CoLaBug.com遵循[CC BY-SA 4.0]分享并保持客观立场,本站不承担此类作品侵权行为的直接责任及连带责任。您有版权、意见、投诉等问题,请通过[eMail]联系我们处理,如需商业授权请联系原作者/原网站。