我正在使用内置的 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" }
}
我遇到的问题:
来自社区的任何见解和方向将不胜感激。谢谢!
您可能需要使用类转换器文档的高级用法部分。本质上,您的
@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。
所以我最初使用
@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
作为杰伊出色答案的替代方案,您还可以创建一个自定义管道,在其中保留将请求有效负载映射/转换为所需 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> {
// ...
}
这是我想出的:
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) {
//...
}