NestJS 在 DTO 创建期间执行验证之前使用 ValidationPipe 转换属性

问题描述 投票:0回答:3

我正在使用内置的 NestJS ValidationPipe 以及类验证器和类转换器来验证和清理入站 JSON 主体有效负载。我面临的一种情况是入站 JSON 对象中混合使用大小写属性名称。我想纠正这些属性并将其映射到我们新的 TypeScript NestJS API 中的标准驼峰式模型,这样我就不会将遗留系统中不匹配的模式耦合到我们的新 API 和新标准,本质上是在DTO 作为应用程序其余部分的隔离机制。例如,入站 JSON 对象的属性:

"propertyone",
"PROPERTYTWO",
"PropertyThree"

应该映射到

"propertyOne",
"propertyTwo",
"propertyThree"

我想使用@Transform 来完成这个,但我认为我的方法不正确。我想知道是否需要编写自定义 ValidationPipe。这是我目前的方法。

控制器:

import { Body, Controller, Post, UsePipes, ValidationPipe } from '@nestjs/common';
import { TestMeRequestDto } from './testmerequest.dto';

@Controller('test')
export class TestController {
  constructor() {}

  @Post()
  @UsePipes(new ValidationPipe({ transform: true }))
  async get(@Body() testMeRequestDto: TestMeRequestDto): Promise<TestMeResponseDto> {
    const response = do something useful here... ;
    return response;
  }
}

测试模型:

import { IsNotEmpty } from 'class-validator';

export class TestMeModel {
  @IsNotEmpty()
  someTestProperty!: string;
}

TestMeRequestDto:

import { IsNotEmpty, ValidateNested } from 'class-validator';
import { Transform, Type } from 'class-transformer';
import { TestMeModel } from './testme.model';

export class TestMeRequestDto {
  @IsNotEmpty()
  @Transform((propertyone) => propertyone.valueOf())
  propertyOne!: string;

  @IsNotEmpty()
  @Transform((PROPERTYTWO) => PROPERTYTWO.valueOf())
  propertyTwo!: string;

  @IsNotEmpty()
  @Transform((PropertyThree) => PropertyThree.valueOf())
  propertyThree!: string;

  @ValidateNested({ each: true })
  @Type(() => TestMeModel)
  simpleModel!: TestMeModel

}

用于 POST 到控制器的示例负载:

{
  "propertyone": "test1",
  "PROPERTYTWO": "test2",
  "PropertyThree": "test3",
  "simpleModel": { "sometestproperty": "test4" }
}

我遇到的问题:

  1. 变换似乎没有效果。类验证器告诉我这些属性中的每一个都不能为空。例如,如果我将“propertyone”更改为“propertyOne”,那么类验证器验证就可以用于该属性,例如它看到了价值。其他两个属性也一样。如果我驼峰式排列它们,那么类验证器很高兴。这是在验证发生之前转换未运行的症状吗?
  2. 这个很奇怪。当我调试和评估 TestMeRequestDto 对象时,我可以看到 simpleModel 属性包含一个包含属性名称“sometestproperty”的对象,即使 TestMeModel 的类定义有一个驼峰命名的“someTestProperty”。为什么 @Type(() => TestMeModel) 不遵守该属性名称的正确大小写? “test4”的值存在于该属性中,因此它知道如何理解该值并分配它。
  3. 仍然很奇怪,TestMeModel 上“someTestProperty”属性的 @IsNotEmpty() 验证没有失败,例如它看到“test4”值并感到满意,即使示例 JSON 有效负载中的入站属性名称是“sometestproperty”,全是小写。

来自社区的任何见解和方向将不胜感激。谢谢!

validation nestjs dto class-validator class-transformer
3个回答
11
投票

您可能需要使用类转换器文档的高级用法部分。本质上,您的

@Transform()
需要看起来像这样something

import { IsNotEmpty, ValidateNested } from 'class-validator';
import { Transform, Type } from 'class-transformer';
import { TestMeModel } from './testme.model';

export class TestMeRequestDto {
  @IsNotEmpty()
  @Transform((value, obj) => obj.propertyone.valueOf())
  propertyOne!: string;

  @IsNotEmpty()
  @Transform((value, obj) => obj.PROPERTYTWO.valueOf())
  propertyTwo!: string;

  @IsNotEmpty()
  @Transform((value, obj) => obj.PropertyThree.valueOf())
  propertyThree!: string;

  @ValidateNested({ each: true })
  @Type(() => TestMeModel)
  simpleModel!: TestMeModel

}

这应该采用传入的有效负载

{
  "propertyone": "value1",
  "PROPERTYTWO": "value2",
  "PropertyThree": "value3",
}

并将其变成您设想的 DTO。

编辑 12/30/2020

所以我最初使用

@Transform()
的想法并没有像预想的那样工作,这真是太可惜了,因为它看起来很漂亮。所以你可以做的不是那么干,但它仍然适用于类转换器,这是一个胜利。通过使用
@Exclude()
@Expose()
你可以使用属性访问器作为奇怪的命名属性的别名,看起来像这样:

class CorrectedDTO {
  @Expose()
  get propertyOne() {
    return this.propertyONE;
  }
  @Expose()
  get propertyTwo(): string {
    return this.PROPERTYTWO;
  }
  @Expose()
  get propertyThree(): string {
    return this.PrOpErTyThReE;
  }
  @Exclude({ toPlainOnly: true })
  propertyONE: string;
  @Exclude({ toPlainOnly: true })
  PROPERTYTWO: string;
  @Exclude({ toPlainOnly: true })
  PrOpErTyThReE: string;
}

现在您可以访问

dto.propertyOne
并获得预期的属性,当您执行
classToPlain
时,它将去除
propertyONE
和其他属性(如果您使用的是 Nest 的序列化拦截器。否则在辅助管道中您可以
plainToClass(NewDTO, classToPlain(value))
其中
NewDTO
只有更正的字段)。

您可能想要研究的另一件事是 automapper 看看它是否有更好的能力来处理这样的事情。

如果你有兴趣,这是我用来测试这个的 StackBlitz


10
投票

作为杰伊出色答案的替代方案,您还可以创建一个自定义管道,在其中保留将请求有效负载映射/转换为所需 DTO 的逻辑。它可以像这样简单:

export class RequestConverterPipe implements PipeTransform{
  transform(body: any, metadata: ArgumentMetadata): TestMeRequestDto {
    const result = new TestMeRequestDto();
    // can of course contain more sophisticated mapping logic
    result.propertyOne = body.propertyone;
    result.propertyTwo = body.PROPERTYTWO;
    result.propertyThree = body.PropertyThree;
    return result;
  }

export class TestMeRequestDto {
  @IsNotEmpty()
  propertyOne: string;
  @IsNotEmpty()
  propertyTwo: string;
  @IsNotEmpty()
  propertyThree: string;
}

然后您可以在控制器中像这样使用它(但您需要确保顺序正确,即

RequestConverterPipe
必须在
ValidationPipe
之前运行,这也意味着
ValidationPipe
不能全局设置):

@UsePipes(new RequestConverterPipe(), new ValidationPipe())
async post(@Body() requestDto: TestMeRequestDto): Promise<TestMeResponseDto> {
  // ...
}

0
投票

这是我想出的:

export class TransformPipe<T> implements PipeTransform {
  constructor(private rules: Record<any, (value: any) => any> = null) {}
  transform(body: T): T {
    const result: T | null = null;
    for (const key in body) {
      if (this.rules[key])
        result[key] = this.rules[key] ? this.rules[key](body[key]) : body[key];
    }
    return result;
  }
}

@UsePipes(
    new TransformPipe<CoolDto>({
        phone: (v) => v?.trim() || '',
        text: (v) => v?.trim() || '',
}),
new ValidationPipe())
@Post('send')
async send(@Body() body: CoolDto) {
    //...
}
© www.soinside.com 2019 - 2024. All rights reserved.