我有一个像这样的自定义方法装饰器。
export function CustomDecorator() {
return applyDecorators(
UseGuards(JwtAuthGuard)
);
}
Run Code Online (Sandbox Code Playgroud)
在自定义装饰器中,我想获取请求标头但不确定如何获取请求实例?
您将无法在类或方法装饰器中获取ExectuionContext对象或Request对象,因为这些装饰器在导入时立即运行。相反,应该做的是制作一个SuperGuard确实ExecutionContext可用的。这SuperGuard应该通过 将所有其他守卫注入其中, constructor 并且根据标题,您应该调用/返回调用的守卫的结果。像这样的东西:
@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);
}
}
}
Run Code Online (Sandbox Code Playgroud)