Nestjs集成swagger api文档

安装依赖

npm i @nestjs/swagger

把swagger添加到项目中:

main.js

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 设置swagger文档相关配置
  const swaggerOptions = new DocumentBuilder()
    .setTitle('测试项目swagger标题')
    .setDescription('测试项目swaggger文档描述')
    .setVersion('1.0')
    .build();
  // 创建文档
  const document = SwaggerModule.createDocument(app, swaggerOptions);
  // 安装
  SwaggerModule.setup('doc', app, document);

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

启动项目

yarn start:dev

 访问swagger文档

http://localhost:3000/doc

 

 为swagger添加参数

import {
    Controller,
    Get,
    Query
} from "@nestjs/common";
import {
    HelloService
} from "./hello.service";
import {
    ApiQuery,
    ApiTags,
    ApiResponse,
    ApiBody,
    ApiParam
} from "@nestjs/swagger";

@ApiTags('hello') // 分组
@Controller('/hello')
export class HelloController {
    constructor(private readonly helloController: HelloService) {}

    @Get()
    @ApiQuery({name: 'message',required:false}) // query参数
    @ApiResponse({
        status: 200,
        description: 'logger'
    })
    logger(@Query() {
        message
    }): string {
        return this.helloController.logger(message);
    }

}

效果

 


版权声明:本文为long_cheng_lv原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。