nestjs - 如何在嵌套 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 中查看它。
谢谢您的帮助。
解决方案
与其使用接口向主体添加类型,不如使用类来执行此操作,然后只需将 @ApiProperty() 装饰器添加到类的每个属性,这是一种更简洁的解决方案,因为您可以避免使用 @ApiBody()装饰师。
此外,在使用类时,您可以利用类验证器装饰器在使用它之前验证主体。
ApiProperty 是从@nestjs/swagger 导出的
更多信息在这里:https ://docs.nestjs.com/openapi/types-and-parameters#types-and-parameters
还要检查有关类验证器的信息:https ://docs.nestjs.com/pipes#class-validator
推荐阅读
- string - 替换文本文件中的单个字符时出现意外结果
- azure - Azure WebJob 代码未通过部署槽交换更新
- reactjs - 对于 Semantic-UI-React Loading 组件后面的这些单选切换,z-index 是否不正确?
- azure-cosmosdb - cosmosdb模拟器为什么会抛出这个错误以及如何解决?
- python - 替代循环遍历所有行熊猫
- javascript - 在同一个函数中使用两个类
- reactjs - 使用反应钩子从 API 重新获取数据
- javascript - 如何显示/隐藏而不是切换图标?
- perl - 在终端上打印脚本的结果(在后台运行)
- json - System.Text.Json.Deserialize 将数组转换为 C# 类