【问题标题】:Explicit types in Request Body not showing up in Swagger (NestJS)请求正文中的显式类型未显示在 Swagger (NestJS) 中
【发布时间】:2021-06-05 05:00:33
【问题描述】:

我正在使用 Swagger 和 NestJs。我的控制器中有以下 API 端点。

@ApiTags('test')
@Controller('test')
export class TestController {
   @Put()
   async create(
       @Body('test') test: {
           name: string,
           age: number
       }): Promise<Foo> {
           return await this.testService.creat(test);
       }
   }
}

不幸的是,swagger 没有选择内联类型定义(或者首先是 body 参数)。如果我用带有@ApiProperty() 注释的类替换内联定义,它就可以工作。但是,我想找到一种使用类的方法。

有没有办法或者我必须在这里使用类?

我也尝试使用ApiBody() 注释,但是它只添加了一个“需要请求正文”字段,而没有在 swagger 中定义类型(见下文)

提前致谢!

【问题讨论】:

  • 如果用一个类来表示body呢?
  • @JayMcDoniel 可以,但我想避免在这里使用类,看看是否有一种方法只使用内联类型定义

标签: swagger nestjs


【解决方案1】:

您必须在 @ApiBody() 标记内指定完整的架构。但是,这只会增加您与实际 @Body() 标记一起管理它的工作量。

@ApiTags('test')
@ApiBody({
            schema: {
                properties: {
                    'name': { type: 'string' },
                    'age': { type: 'number' }
                }
            }
         })
@Controller('test')
export class TestController {
   @Put()
   async create(
       @Body('test') test: {
           name: string,
           age: number
       }): Promise<Foo> {
           return await this.testService.creat(test);
       }
   }
}

我建议按照 Jay 的建议使用类。

【讨论】:

    猜你喜欢
    • 2020-09-14
    • 2022-11-11
    • 2020-06-16
    • 2022-06-13
    • 1970-01-01
    • 2023-02-02
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多