decorator - 在 NestJS 中,如何在自定义方法装饰器中获取执行上下文或请求实例?

标签 decorator nestjs

我有一个像这样的自定义方法装饰器。

export function CustomDecorator() {

    return applyDecorators(
        UseGuards(JwtAuthGuard)
    );
}

在自定义装饰器中,我想获取请求 header 但不确定如何获取请求实例?

最佳答案

您将无法在类或方法装饰器中获取 ExectuionContext 对象或 Request 对象,因为这些装饰器在导入时立即运行.相反,应该做的是制作一个 SuperGuard ,它确实有 ExecutionContext 可供使用。这个 SuperGuard 应该通过 constructor 将所有其他防护注入(inject)其中,并且根据 header ,您应该调用/返回被调用防护的结果。像这样的:

@Injectable()
export class SuperGuard implements CanActivate {
  constructor(
    private readonly jwtAuthGuard: JwtAuthGuard,
    private readonly googleAuthGuard: GoogleAuthGuard,
  ) {}

  canActivate(context: ExecutionContext) {
    const req = context.switchToHttp().getRequest();
    if (req.headers['whatever'] === 'google') {
      return this.googleAuthGuard.canActivate(context);
    } else {
      return this.jwtAuthGuard.canActivate(context);
    }
  }
}

关于decorator - 在 NestJS 中,如何在自定义方法装饰器中获取执行上下文或请求实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63496404/

相关文章:

nestjs - nrwl nx 命令为嵌套模块生成 lib

typescript - 如何将实例变量传递给 typescript 装饰器参数?

Python:编写接受参数的装饰器的快捷方式?

ruby-on-rails-3 - ActiveRecord 关联上的装饰器模式和类型不匹配

javascript - 在 NestJS 中测试解析器

swagger - Nestjs Swagger 4 的循环依赖

Python:如何从类装饰器内部访问装饰类的实例?

Decorator 和 decorated 类在不同的 bean archives 中

apache-kafka - Nestjs中的NestFactory.create可以订阅kafka上的topic吗?

typescript - @Transform() Boolean Cast 不适用于 DTO