首页 > 解决方案 > 如何在嵌套 js 中添加对象以输入 ApiBody 装饰器

问题描述

我有一个带有 POST 操作的控制器来保存 ReasonCode。这是我的控制器中的内容:

import {
  CustomAuthGuard,
  ReasonCodeService,
  ReasonCode,
} from 'cnv-ms-core';

export class ReasonCodeController {
    constructor(private readonly reasonCodeService: ReasonCodeService) {}
}

  @Post('reason-codes')
    @ApiOperation({ summary: 'Save Reason Code' })
    @ApiBody({
        //type: ReasonCode,
        description: 'Reason Code',
        required: true,
        isArray: false,
    })
    @ApiResponse({
        status: 201,
        description: 'Reason Code is Saved Successfully.'
    })  
  async saveReasonCode(
    @Body() newReasonCode: ReasonCode,
  ): Promise<ReasonCode | null> {
    return this.reasonCodeService.saveReasonCode(newReasonCode);
  }

这是我的接口对象:

export interface ReasonCode {
    name: string;
    description: string;
    type: ReasonCodeTypeEnum;
    isVisible: boolean;
    createdAt?: Date;
    updatedAt?: Date;
}

正如您在上面的控制器片段中看到的那样,我在“@ApiBody”装饰器中注释掉了“类型”。我想添加这个,但是当我取消注释时,我看到错误“ReasonCode 仅指一种类型,但在此处用作值”,并且 vs code 提供了将 ReasonCode 添加到导入的快速修复。但是,我已经在导入中有 ReasonCode。如何在 @ApiBody 中添加它以在 swagger-ui 中查看它。

谢谢您的帮助。

标签: nestjsnestjs-swagger

解决方案


与其使用接口向主体添加类型,不如使用类来执行此操作,然后只需将 @ApiProperty() 装饰器添加到类的每个属性,这是一种更简洁的解决方案,因为您可以避免使用 @ApiBody()装饰师。

此外,在使用类时,您可以利用类验证器装饰器在使用它之前验证主体。

ApiProperty 是从@nestjs/swagger 导出的

更多信息在这里:https ://docs.nestjs.com/openapi/types-and-parameters#types-and-parameters

还要检查有关类验证器的信息:https ://docs.nestjs.com/pipes#class-validator


推荐阅读