NestJs 在自定义验证器(类验证器)中获取请求实例或执行上下文

use*_*505 8 typescript class-validator nestjs

是否可以在 nestJs(类验证器 => 自定义验证器)中注入执行上下文或访问当前请求?

import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';
import { Injectable } from '@nestjs/common';
import { Connection } from 'typeorm';
import { InjectConnection } from '@nestjs/typeorm';

@ValidatorConstraint({ name: 'modelExistsConstraint', async: true })
@Injectable()
export class ModelExistsConstraint implements ValidatorConstraintInterface {

  constructor(
    @InjectConnection('default') private readonly connection: Connection,
  ) {
  }

  async validate(value: string, validationArguments: ValidationArguments) {
    // here need request or execution context;
    // const test = this.context.switchToHttp().getRequest();
    const model = await this.connection
      .getRepository(validationArguments.constraints[0])
      .findOne({ where: { [validationArguments.property]: value } });
    return !model;
  }

  defaultMessage(args: ValidationArguments) {
    return `Model with "${args.property}" - "${args.value}" already exists`;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 0

我认为你应该使用类似库ClsModule中的东西nestjs-cls,这将允许你从请求中获取变量。因为如果您将 DTO 与 ValidationPipe 一起使用,它将无法访问执行上下文。

此外,这将允许您拥有单例服务而不是REQUEST范围内的服务。