【问题标题】:NestJS API Accept one OR other Type in request bodyNestJS API 在请求正文中接受一个或其他类型
【发布时间】:2020-10-14 19:21:58
【问题描述】:

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

控制器路由

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;
}

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

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

这也不起作用。 我不认为我正在接近这个权利,但我在网上也找不到太多关于这方面的信息,你有什么线索可以建议吗?

【问题讨论】:

    标签: api nestjs class-validator


    【解决方案1】:

    这与 class-transformer 包有关。您可以通过定义一个鉴别器来归档它,如下所述: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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 2020-12-20
      • 2020-09-22
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 2016-02-29
      相关资源
      最近更新 更多