首页 > 其他分享 >nestjs中swagger的基本使用

nestjs中swagger的基本使用

时间:2022-12-27 10:57:45浏览次数:35  
标签:基本 name dog Controller ApiTags nestjs swagger

nestjs中swagger的基本使用

安装

$ npm install --save @nestjs/swagger swagger-ui-express
//如果使用fastify,则必须安装fastify-swagger而不是swagger-ui-express:
$ npm install --save @nestjs/swagger fastify-swagger

朴素使用

main.ts

import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

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

  const config = new DocumentBuilder()
    .setTitle('this is a title')
    .setDescription('this is a description')
    .setVersion('1.0')
    .addTag('cat')
    .addTag('dog')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}

重点:用ApiTags装饰每一个Controller,才能把它们按名字分类展示

import { ApiTags } from '@nestjs/swagger';

app.controller.ts

@ApiTags()
@Controller()
export class AppController { ... }

cat.controller.ts

@ApiTags('cat')
@Controller('cat')
export class CatController { ... }

dog.controller.ts

@ApiTags('dog')
@Controller('dog')
export class DogController { ... }

如上便得到如下效果:

通过装饰器对接口更详细地说明

import { Controller, Get, Param } from '@nestjs/common';
import { ApiTags, ApiParam } from '@nestjs/swagger';

@ApiTags('dog')
@Controller('dog')
export class DogController {
  @Get('/onedog/:name')
  // 通过ApiParam装饰器,来描述接口需要哪些参数
  @ApiParam({ name: 'name', type: String, description: '姓名' })
  @ApiParam({ name: 'gender', type: String, description: '性别' })
  aGetRequest(
    @Param('name') name: string, 
    @Param('gender') gender: string
  ): string { 
    return `a ${gender} named ${name} has lunched a get request`
  }
}

如上便得到如下效果:

除了ApiParam装饰器外还有很多别的装饰器可用,可自行百度,用法大同小异

标签:基本,name,dog,Controller,ApiTags,nestjs,swagger
From: https://www.cnblogs.com/Lilc20201212/p/17007579.html

相关文章