nestjs - 05

Nestjs swagger接口文档

1、安装模块
npm i @nestjs/swagger swagger-ui-express
2、配置
// main.ts 配置
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'

async function bootstrap()  {
  const app = await NestFactory.create(AppModule)
  // swagger 配置
  const options = DocumentBuilder().set('swagger文档的标题').setDescription('文档描述信息').setVersion('文档版本号 eg: 1').build()
  const document = SwaggerModule.createDocument(app, options)
  // 设置文档路径: eg: localhost:3000/api-docs 
  SwaggerModule.setup('/api-docs', app, document)
}
3、常用decorator 配置
// controller.ts
import { Controller, Get } from '@nestjs/common'
import { ApiTags, ApiParam, ApiQuery, ApiResponse, ApiOperation, ApiBearerAuth } from '@nestjs/swagger'

@Controller()
// api分组 ,如图 1-1
@ApiTags('测试接口')
export class DemoController {
  
  @Get()
	// 接口描述 如图 1-2
  @ApiOperation({ summary: '接口名称', description: '更详细的描述' })
  // 查询参数藐视
  @ApiQuery({ name: 'page', description: '分页信息描述', required: true, type: Number })
  // 自定义返回描述信息 如图1-4
  @ApiResponse({ status: 403, description: '自定义描述信息' })
  findAll() {
    return 'all'
  }
  
  @Get(':id')
  // 动态参数描述 如图 1-3
  @ApiParam({ name: 'id', description: '详细描述', required: true, type: Number })
  findOne(id) {
    return 'select one'
  }
}


// create.dot.ts 
// post的参数装饰 ApiProperty
import { ApiProperty } from '@nestjs/swagger'

export class CreateDto {
  // 如 图1-5
  @ApiProperty()
  name: string
  @ApiProperty()
  age: number
}

// controller
export class DemoController {
  @Post()
  create(@Body() createDto: CreateDto) {
    
  }
}

添加接口 jwt 权限控制(如 图1-6)

// main.ts
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
// swagger 配置 添加权限配置 addBearerAuth
const options = DocumentBuilder().addBearerAuth().set('swagger文档的标题').setDescription('文档描述信息').setVersion('文档版本号 eg: 1').build()


// controller.ts
import { ApiBearerAuth } from '@nestjs/swagger'
@Controller()
@ApiBearerAuth()
export class DemoController() {}

图1-1

图1-1

图1-2

图1-2

图1-3

图1-3

图1-4

图1-4

图1-5

图1-5

图1-6

图1-6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值