且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NestJS 在 GraphQL 解析器中获取通过 JWT 进行身份验证的当前用户

更新时间:2023-12-01 11:24:04

终于找到答案了... https://github.com/nestjs/graphql/issues/48#issuecomment-420693225 为我指明了创建用户装饰器

Finally found the answer ... https://github.com/nestjs/graphql/issues/48#issuecomment-420693225 pointed me into the right direction of creating a user decorator

// user.decorator.ts
import { createParamDecorator } from '@nestjs/common';

export const CurrentUser = createParamDecorator(
  (data, req) => req.user,
);

然后在我的解析器方法中使用它:

And then use this in my resolver method:

 import { User as CurrentUser } from './user.decorator';

 @Query(returns => User)
  @UseGuards(GqlAuthGuard)
  whoami(@CurrentUser() user: User) {
    console.log(user);
    return this.userService.findByUsername(user.username);
  }

现在一切都按预期进行.所以这个答案的所有功劳都归于 https://github.com/cschroeter

Now everything works as expected. So all credits of this answer goes to https://github.com/cschroeter