【问题标题】:NestJs - Validate request body using class-validator having 2 options for body classNestJs - 使用具有 2 个主体类选项的类验证器验证请求主体
【发布时间】:2021-09-24 13:49:37
【问题描述】:

我有一个休息电话,它可能会收到 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 个或更多类并使用类验证器验证它们? 我不想使用同一个类..

谢谢大家:)

【问题讨论】:

  • bodyDto: (ClassA | ClassB) 未验证,即 typescript 的类型声明
  • 可以使用拦截

标签: node.js typescript nestjs class-validator


【解决方案1】:
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 {
   ...
}

【讨论】:

  • 为什么在另一个管道上使用拦截器?
【解决方案2】:

我不想使用同一个类..

那么这是不可能的,至少对于 Nest 的内置 ValidationPipe 来说是不可能的。 Typescript 不反映联合、交集或其他类型的泛型类型,因此没有返回此参数的元数据,如果没有可操作的元数据,Nest 最终会跳过管道。

您可能会创建一个自定义管道来为您进行验证,如果您有两种类型,您可能必须这样做。您仍然可以在类内部调用适当的class-transformerclass-validator 方法。

【讨论】:

    猜你喜欢
    • 2022-08-02
    • 2021-07-24
    • 2021-12-10
    • 2019-08-29
    • 1970-01-01
    • 2021-02-03
    • 2021-03-09
    • 2019-05-16
    • 1970-01-01
    相关资源
    最近更新 更多