在 NestJS 中,有没有办法将数据从 Guards 传递到控制器?

Agn*_*bha 4 javascript express nestjs fastify

所以我目前在我的组织中广泛使用 NestJS。出于身份验证的目的,我们使用我们自己的守卫。所以我的问题是,如果有任何方法可以将数据从警卫传递到控制器,除了response.localsexpressjs ,任何人都可以指导我吗?这对框架造成了严重的依赖,我现在不希望这样。

TIA。

Jay*_*iel 9

将数据从 Guard 传递到控制器的唯一可能方法是将数据附加到请求中的字段或使用某种元数据反射,这可能会变得更具挑战性。

在你的警卫中,你可以有这样的canActivate功能

canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
  const req = context.switchToHttp().getRequest();
  if (/* some logic with req */) {
    req.myData = 'some custom value';
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)

然后在您的控制器中,您可以拉动绳子req.myData并将其some custom value取回。


Tha*_*ang 7

您可以创建自定义装饰器来获取数据,而不是使用 Guard:

export const Authorization = createParamDecorator((_, request: any) => {
  const { authorization: accessToken } = request.headers;
  try {
    const decoded = jwt.verify(accessToken, process.env.JWT_HASH);
    return pick(decoded, 'userId');
  } catch (ex) {
    throw new InvalidToken();
  }
});

export interface AuthUser {
  userId: string;
}
Run Code Online (Sandbox Code Playgroud)

并像这样传递给您的控制器:

  @Post()
  createFeedback(
    @Body() body: FeedbackBody,
    @Authorization() user: AuthUser,
  ): Promise<Feedback> {
    body.userId = user.userId;
    return this.feedbackService.feedback(body, user);
  }
Run Code Online (Sandbox Code Playgroud)

这可以起到保护作用,因为当您的令牌无效时,它会抛出异常