【问题标题】:NestJS access response object in pipesNestJS 访问管道中的响应对象
【发布时间】:2019-10-30 21:56:49
【问题描述】:

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

这是我的验证管道。

@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);
  }
}

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

【问题讨论】:

    标签: node.js typescript nestjs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多