node.js - NestJS 访问管道中的响应对象

标签 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);
  }
}

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

最佳答案

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

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

关于node.js - NestJS 访问管道中的响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56629059/

相关文章:

javascript - 如何仅使用 Nest.js 框架中的依赖注入(inject)容器?

javascript - NestJS 的自定义路由装饰器

node.js - 如何编写针对路径参数中的操作的路由

node.js - 来自图形魔法的缩略图,没有放大

typescript - Dart-如何强制将 map 关键字包含在列表字符串中

typescript - 错误 : Cannot find module '@vue/cli-plugin-babel/preset'

javascript - nestjs框架中接口(interface)的作用

node.js - Express.js - 如何将 url 参数从主路由器传递到另一个路由器模块?

Node.js 意外 token R

c# - 使用多接口(interface)继承的 typescript 名称冲突/冲突