Nest.js学习之路(26)-用Nestjs Decorator建立Swagger API Doc

作者 : 开心源码 本文共3260个字,预计阅读时间需要9分钟 发布时间: 2022-05-12 共251人阅读

在nestjs下可以用相似ASP.net core或者是Java中相似的reflection机制方式,利用Decorators及Swagger Module自动产生API文件页面。

安装套件

yarn add @nestjs/swagger

产生最简单的Swagger API说明页面

在main.ts下,加入产生Swagger页面的代码

async function bootstrap() {    const app = await NestFactory.create(AppModule);    const userApiOptions = new DocumentBuilder()        .setTitle('User API Doc')        .setDescription('User API Info')        .setVersion('1.0')        .addBearerAuth()        .addTag('users') // match tags in controllers        .build();    const userApiDocument = SwaggerModule.createDocument(app, userApiOptions, {include: [UserModule]});    SwaggerModule.setup('v1/api/', app, userApiDocument); await app.listen(3000);}

启动nestjs

2018112401.png

可以看到Parameter底下UserDTO没有相关信息

设定Swagger物件参数

传递物件参数包含@Body、@Query所参考到的物件,如UserDTO、userQueryDTO,要在Swagger页面显示参数信息,通过@ApiModelProperty

userDTO.ts

export class UserDTO {    @ApiModelProperty({        maxLength: 10,        description: 'Username',    })    name: string;    @ApiModelProperty()    age: number;    @ApiModelProperty()    platId: number;    @ApiModelProperty()    plat: Platform;    // @IsNumber({    //  allowNaN: false,    //  allowInfinity: false,    //  }, { each: true, // 检查阵列每一个元素能否都是数字    // })    @ApiModelProperty({required: false})    roleIds: number[];    @ApiModelProperty()    roles: Role[];}

2018112402.png

userQueryDTO

export class UserQueryDTO{    @ApiModelProperty({        description: 'username keyword',    })    @IsString()    name: string;    @ApiModelProperty({        description: 'Page No',        default: 1,    })    @IsNumber()    page: number;    @ApiModelProperty({        description: 'Records Per Page',        default: 5,    })    @IsNumber()    pageSize: number;}

2018112403.png

Http Reponse回传信息

不同Http回应的code显示讯息,通过@ApiOkResponse、@ApiCreatedResponse等来套用在controller下对应的方法,详细@ApixxResponse清单上官网查询

以user.controller为例

@ApiUseTags('users')@ApiBearerAuth()@ApiForbiddenResponse({description: 'Unauthorized'})@UseGuards(AuthGuard())@Controller('user')export class UserController {   constructor(       private readonly userService: UserService,   ) {}   @Post()   // 回传201的形容   @ApiCreatedResponse({description: 'User Created'})   // 回传Internal Error的形容   @ApiInternalServerErrorResponse({description: 'Invalid Input'})   addUser(@Body() userDTO: UserDTO) {       return this.userService.addUser(userDTO);   }   @ApiOkResponse({description: 'Return Users '})   @Get()   getUsers(@Query() query: UserQueryDTO) {       return this.userService.getUsers(query);   }   @Get(':userId')   getUserById(@Param('userId') id) {       return this.userService.getUserById(id);   }   @Delete(':userId')   deleteUser(@Param('userId') id) {       return this.userService.deleteUser(id);   }}

可以根据Exeception Filter显示的message来设定Error类的Response的形容

2018112601.png

以Module来区分Swagger页面

Swagger Module是依据Module来区分页面,现在的专案下,只有UserModule跟AuthModule,可以用不同路径来区分

main.ts

async function bootstrap() {    const app = await NestFactory.create(AppModule);    const userApiOptions = new DocumentBuilder()        .setTitle('User API Doc')        .setDescription('User API Info')        .setVersion('1.0')        .addBearerAuth()        .addTag('users') // match tags in controllers        .build();    const userApiDocument = SwaggerModule.createDocument(app, userApiOptions, {include: [UserModule]});    SwaggerModule.setup('v1/api/user', app, userApiDocument);    const authApiOptions = new DocumentBuilder()            .setTitle('Auth API Doc')            .setDescription('Auth API Info')            .setVersion('1.0')            .addBearerAuth()            .addTag('auth') // match tags in controllers                        .build();    const authApiDocument = SwaggerModule.createDocument(app, authApiOptions, {include: [AuthModule]});    SwaggerModule.setup('v1/api/auth', app, authApiDocument); await app.listen(3000);}bootstrap();

2018112602.png

Auth API独立另外一个页面

推荐一下我的公众号: 【 geekjc 】,微信号: 【 c8706288 】一起学习交流编程知识,分享经验,各种有趣的事。

tuiguang.png

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Nest.js学习之路(26)-用Nestjs Decorator建立Swagger API Doc

发表回复