NestJS 访问管道中的响应对象

Tah*_*gun 4 node.js typescript nestjs

我正在使用管道进行请求验证。如果请求失败,我想重定向页面但不想抛出错误。问题是如何在验证中访问响应对象。

这是我的验证管道。

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  async transform(value: any, { metatype }: ArgumentMetadata) {
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
     // in here i need to response with res.redirect('') function
      throw new BadRequestException('Validation failed');
    }
    return value;
  }
  private toValidate(metatype: Function): boolean {
    const types: Function[] = [String, Boolean, Number, Array, Object];
    return !types.includes(metatype);
  }
}
Run Code Online (Sandbox Code Playgroud)

我需要访问 res.redirect() 函数而不是抛出异常

Jay*_*iel 5

response对象在 a 的上下文中不可用pipe。您可以做的是 A) 使用interceptor替代或 B) 抛出异常并使用 afilter来捕获此特定异常并重定向到正确的位置。

Pipes 仅用于验证或对象转换,因此立即返回成功(带有可能转换的对象)或抛出有关转换/验证失败原因的错误。