【问题标题】:How can I add an Object to type in ApiBody decorator in nest js如何在嵌套 js 中添加对象以输入 ApiBody 装饰器
【发布时间】:2021-06-29 15:01:44
【问题描述】:

我有一个带有 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;
}

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

感谢您的帮助。

【问题讨论】:

  • 为什么不创建一个 DTO 类,而是键入所有 api 属性?

标签: nestjs nestjs-swagger


【解决方案1】:

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

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

ApiProperty 是从 @nestjs/swagger 导出的

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

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

【讨论】:

  • 我将它更改为一个类,现在我看到以下错误:找不到模块:错误:无法解析“缓存管理器”找不到模块:错误:无法解析“类-变压器'找不到模块:错误:无法解析'class-transformer / storage'模块找不到:错误:无法解析'class-validator'模块找不到:错误:无法解析'express'模块找不到: 错误:无法解析“fastify-swagger”模块未找到:错误:无法解析“路径”
  • 使用命令安装包:npm i class-validator class-transformer
  • 另外,你用的是 express 还是 fastify with nest?
  • 让我看看你的班级是否一切正常
  • 非常感谢您的帮助。我将查看文件夹结构,看看是否能找到一些东西。
【解决方案2】:

export interface ReasonCode 更改为export class ReasonCode 可能会解决此问题

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2010-11-28
    • 2023-01-12
    • 1970-01-01
    • 2016-06-11
    相关资源
    最近更新 更多