我使用内置的 NestJS ValidationPipe 以及类验证器和类转换器来验证和清理入站 JSON 正文有效负载。我面临的一种情况是入站 JSON 对象中混合使用大小写属性名称。我想在新的 TypeScript NestJS API 中纠正这些属性并将其映射到标准的驼峰式模型,这样我就不会将遗留系统中不匹配的模式耦合到我们的新 API 和新标准,本质上是使用 @Transform DTO 作为应用程序其余部分的隔离机制。例如,入站 JSON 对象的属性:
"propertyone",
"PROPERTYTWO",
"PropertyThree"
Run Code Online (Sandbox Code Playgroud)
应该映射到
"propertyOne",
"propertyTwo",
"propertyThree"
Run Code Online (Sandbox Code Playgroud)
我想使用 @Transform 来完成此任务,但我认为我的方法不正确。我想知道是否需要编写自定义 ValidationPipe。这是我目前的方法。
控制器:
"propertyone",
"PROPERTYTWO",
"PropertyThree"
Run Code Online (Sandbox Code Playgroud)
测试我模型:
"propertyOne",
"propertyTwo",
"propertyThree"
Run Code Online (Sandbox Code Playgroud)
测试我请求Dto:
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 …Run Code Online (Sandbox Code Playgroud)