api - NestJS API 接受请求正文中的一种或其他类型

标签 api nestjs class-validator

我有一个创建 Controller ,它在 PG 数据库中执行 CRUD 之前对 JSON 数据进行严格的验证。 我正在尝试实现多种类型之一的验证。

Controller 路由

async create(@Body() newSheet: CreateSheetsDto) {
        
        return this.sheetService.create(newSheet);
    }

DTO

import { ApiProperty } from '@nestjs/swagger';
import {ValidateNested} from "class-validator";
import { Type } from 'class-transformer';
import { BodyValidator} from "../validators/BodyValidator";

export class CreateSheetsDto {  })
    @ValidateNested({ each: true })
    @Type(() => BodyValidator)
    readonly body: BodyValidator;
}

在多个子键上有多层 JSON 验证。 我尝试在 @Type 回调中使用 OR 运算符,相当直观。结果不起作用

export class CreateSheetsDto { //test
    @ApiProperty({ type: BodyValidator || TypeTwoValidator })
    @ValidateNested({ each: true })
    @Type(() => BodyValidator || TypeTwoValidator)
    readonly body: BodyValidator | TypeTwoValidator;
}

我还尝试在 Controller 中使用联合运算符,并创建另一个特定于另一种类型的 DTO,例如:

async create(@Body() newSheet: CreateSheetsDto | CreateSheetsTypeTwoDto) {
        
        return this.sheetService.create(newSheet);
    }

这也不起作用。 我认为我的做法不对,但我也无法在网上找到太多相关信息,您可以提供任何建议吗?

最佳答案

这与类转换器包有关。您可以通过定义鉴别器来存档它,如下所述:https://github.com/typestack/class-transformer#providing-more-than-one-type-option

示例:

export class Album {
  id: number;
  name: string;

  @Type(() => Photo, {
    discriminator: {
      property: '__type',
      subTypes: [
        { value: Landscape, name: 'landscape' },
        { value: Portrait, name: 'portrait' },
        { value: UnderWater, name: 'underwater' },
      ],
    },
  })
  topPhoto: Landscape | Portrait | UnderWater;
}

关于api - NestJS API 接受请求正文中的一种或其他类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62556649/

相关文章:

javascript - 在 api 调用期间捕获错误不起作用?

api - 在 Google Spreadsheet API 上获取合并单元格宽度

node.js - API Controller : Cannot PUT,无法删除(404未找到)

unit-testing - 开 Jest 测试 DTO 装饰器。在 Jest SPEC 文件中失败,但可以通过 Postman 运行

Java api - 以 _ [下划线] 开头的类名

Windows 进程关联

event-handling - 无法捕获 NestJs 中的事件

node.js - 如何在Nestjs中实现多种 Passport JWT身份验证策略

javascript - 类验证器:验证数值的位数