[英]NestJs - Validate request body using class-validator having 2 options for body class
我有一个休息电话,它可能会收到 classA 或 classB 类型的主体。 我需要将它保留为 2 个不同的类。 例子 -
// classes -
class ClassA {
@IsString()
@Length(1, 128)
public readonly name: string;
@IsString()
@Length(1, 128)
public readonly address: string;
}
class ClassB {
@IsString()
@Length(1, 10)
public readonly id: string;
}
// my request controller -
@Post('/somecall')
public async doSomething(
@Body(new ValidationPipe({transform: true})) bodyDto: (ClassA | ClassB) // < not validating any of them..
): Promise<any> {
// do something
}
问题是,当有多个类时,body 不会被验证。
如何使用 2 个或更多类并使用类验证器验证它们? 我不想使用同一个类..
谢谢你们 :)
我不想使用同一个类..
那么这是不可能的,至少对于 Nest 的内置ValidationPipe
是不可能的。 Typescript 不反映联合、交集或其他类型的泛型类型,因此此参数没有返回的元数据,如果没有可操作的元数据,Nest 最终将跳过管道。
您可能会创建一个自定义管道来为您进行验证,如果您有两种类型,您可能不得不这样做。 您仍然可以在class-transformer
调用适当的class-transformer
和class-validator
方法。
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { of } from 'rxjs';
@Injectable()
export class CheckTypeInterceptor implements NestInterceptor {
constructor() {}
async intercept(context: ExecutionContext, next: CallHandler) /*: Observable<any>*/ {
const httpContext = context.switchToHttp();
const req = httpContext.getRequest();
const bodyDto = req.body.bodyDto;
// Need Update below logic
if (bodyDto instanceof ClassA || bodyDto instanceof ClassB) {
return next.handle();
}
// Return empty set
return of([]);
}
}
@UseInterceptors(CheckTypeInterceptor)
export class ApiController {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.