简体   繁体   English

NestJS - 当前身份验证用户,但不是通过装饰器

[英]NestJS - current auth user but not via decorator

I create belowed decorator to get current logged in to the system user,我创建了下面的装饰器来获取当前登录到系统用户,

export const CurrentUser = createParamDecorator(
    (data: unknown, ctx: ExecutionContext) => {
      const request = ctx.switchToHttp().getRequest();
      return request.user;
    },
  );

but I do not want to use this because i need to use in any of my controller which is a bit troublesome for me because some functions are optional, ie both for the logged in user and the non logged in user,但我不想使用它,因为我需要在我的任何 controller 中使用这对我来说有点麻烦,因为有些功能是可选的,即对于登录用户和未登录用户,

so, how can I get current logged in user in my service in functions when i want to get current user instead of all via decorator in controller?那么,当我想获取当前用户而不是全部通过 controller 中的装饰器时,如何在我的service中获取当前登录用户?

thanks for any help谢谢你的帮助

You'd have to make a custom provider and inject the request into it.您必须创建一个自定义提供程序并将请求注入其中。 Something like this像这样的东西

{
  provider: 'CURRENT_USER',
  inject: [REQUEST],
  useFactory: (req: Request) => {
    return req.user;
  },
  scope: Scope.REQUEST,
}

( REQUEST is injected from @nestjs/core ) REQUEST@nestjs/core注入)

Then the user can be injected into the service with @Inject('CURRENT_USER') .然后可以使用@Inject('CURRENT_USER')将用户注入到服务中。 Keep in mind, this will make the service REQUEST scoped, and by scope hierarchy it will make whatever you inject the service into REQUEST scoped.请记住,这将使服务REQUEST作用域,并且通过scope 层次结构,它将使您将服务注入到REQUEST作用域中的任何内容。

Edit 2/15/21 21 年 2 月 15 日编辑

An example of this module could look something like this:此模块的示例可能如下所示:

@Module({
  providers: [{
    provider: 'CURRENT_USER',
    inject: [REQUEST],
    useFactory: (req: Request) => {
      return req.user;
    },
    scope: Scope.REQUEST,
  }],
  exports: ['CURRENT_USER'],
})
export class CurrentUserModule {}

And now in whatever module that has the service that needs the current user you do现在在任何具有需要当前用户的服务的模块中

@Module({
  imports: [CurrentUserModule],
  providers: [ServiceThatNeedsUser],
})
export class ModuleThatNeedsUser {}

and in the service:并在服务中:

@Injectable()
export class ServiceThatNeedsUser {
  constructor(@Inject('CURRENT_USER') private readonly user: UserType) {}

  // rest of class implementation
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM