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

In NestJS, how to get execution context or request instance in custom method decorator?

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

export function CustomDecorator() {

    return applyDecorators(
        UseGuards(JwtAuthGuard)
    );
}

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

您将无法在 class 或方法装饰器中获得 ExectuionContext object 或 Request object,因为这些装饰器在导入时立即 运行。相反,应该做的是使 SuperGuard 确实具有 ExecutionContext 可用。这个 SuperGuard 应该通过 constructor 将所有其他守卫注入其中,并且根据 header 你应该 call/return 守卫调用的结果。像这样:

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