简体   繁体   中英

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,

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?

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 )

Then the user can be injected into the service with @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.

Edit 2/15/21

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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