使用@nestjs/swagger+nest-knife4j

547 阅读2分钟

前言

找了好久的文档,都没有nest-knife4j文档,网上相关的教程也比较少,所以总结一下。 下方有源码地址,请放心食用

效果图

废话不多说,先看效果图

访问:http://127.0.0.1:3000/api/swagger image.png

访问:http://127.0.0.1:3000/doc.html image.png

安装

pnpm install @nestjs/swagger nest-knife4j

相关版本:

    "nest-knife4j": "^1.0.1",
    "@nestjs/swagger": "^7.4.0",

主要代码

main.ts文件

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { knife4jSetup } from 'nest-knife4j';

const PORT = 3000;
const NAME = 'nest-swagger-demo';
const VERSION = '1.0.0';

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

  const options = new DocumentBuilder()
  .addBearerAuth({
    type: 'http',
    scheme: 'bearer',
    bearerFormat: 'JWT',
    name: 'Authorization',
    description: 'Enter JWT token',
    in: 'header',
  }, 'Authorization')
  .addGlobalParameters({
    name: 'X-Lang',
    in: 'header',
    description: '国际化语言,英语: enUs; 中文简体: zhCN; 中文繁体: zhTW;',
    example: 'zhCN',
    required: false
  }, {
    name: 'X-Version',
    in: 'header',
    description: '版本号控制, 1 ,2 ',
    example: '1',
    required: false
  })
    .setTitle(NAME)
    .setDescription(`${NAME}-${VERSION} API description`)
    .setVersion(VERSION)
    .addServer(`http://127.0.0.1:${PORT}/`, 'Local environment')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('/api/swagger', app, document);
  knife4jSetup(app, [
    {
      name: NAME,
      url: `/api/swagger-json`,
      swaggerVersion: VERSION,
      location: `/api/swagger-json`,
    },
  ]);

  await app.listen(PORT);

  console.log(
    `nest-swagger-demo is running at http://127.0.0.1:${PORT}; 
     swagger Doc running at http://127.0.0.1:${PORT}/api/swagger; 
     knife4j Doc running at http://127.0.0.1:${PORT}/doc.html;`,
  );
}
bootstrap();

在.controller.ts文件中的应用

import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiBody, ApiParam } from '@nestjs/swagger';
import { BookService } from './book.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';

@ApiTags('书籍')
@ApiBearerAuth('Authorization')
@Controller('book')
export class BookController {
  constructor(private readonly bookService: BookService) { }

  @Post()
  @ApiOperation({ summary: '创建书籍' })
  @ApiResponse({ status: 200, description: '创建书籍' })
  create(@Body() createBookDto: CreateBookDto) {
    return this.bookService.create(createBookDto);
  }

  @Get()
  @ApiOperation({ summary: '获取书籍列表' })
  @ApiResponse({ status: 200, description: '获取书籍列表' })
  findAll() {
    return this.bookService.findAll();
  }

  @Get(':id')
  @ApiOperation({ summary: '获取书籍详情' })
  @ApiResponse({ status: 200, description: '获取书籍详情' })
  findOne(@Param('id') id: string) {
    return this.bookService.findOne(+id);
  }

  @Patch(':id')
  @ApiOperation({ summary: '更新书籍' })
  @ApiResponse({ status: 200, description: '更新书籍' })
  @ApiBody({
    description: '更新书籍参数',
    type: UpdateBookDto,
  })
  @ApiParam({
    name: 'id',
    type: 'string',
    example: '1'
  })
  update(@Param('id') id: string, @Body() updateBookDto: UpdateBookDto) {
    return this.bookService.update(+id, updateBookDto);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除书籍' })
  @ApiResponse({ status: 200, description: '删除书籍' })
  @ApiParam({
    name: 'id',
    type: 'string',
    example: '1'
  })
  remove(@Param('id') id: string) {
    return this.bookService.remove(+id);
  }
}

在.dto.ts文件中的应用

import { ApiProperty } from '@nestjs/swagger';
import { Length, IsNotEmpty, IsOptional } from 'class-validator';
export class CreateBookDto {
  @ApiProperty({ description: '书名', required: true, example: '书名' })
  @IsNotEmpty({ message: '书名不能为空' })
  @Length(1, 50, {
    message: `用户名长度必须大于$constraint1到$constraint2之间,当前传递的值是$value`,
  })
  name: string;

  @ApiProperty({
    description: '描述',
    required: false,
    example: '描述描述描述描述描述描述',
  })
  @IsNotEmpty({ message: '描述不能为空' })
  @IsOptional()
  description: string;

  @ApiProperty({ description: '作者', required: true, example: 'faker' })
  @IsNotEmpty({ message: '作者不能为空' })
  author: string;
}

相关文档

源码地址

完结撒花。。。