NodeJS NestJs:在RolesGaurd中注入UserService

xyhw6mcr  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(116)

我有一个UserService,从用户模块导出如下:

@Module({
  imports: [
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
    MongooseModule.forFeature([{ name: Profile.name, schema: ProfileSchema }]),
  ],
  controllers: [UserController],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}

字符串

罗莱斯高德酒店

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    @Inject(UserService) private readonly userService: UserService,
  ) {}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const roles = this.reflector.get(Roles, context.getHandler());
    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    const params = request.params;

    if (!roles.includes(user.role)) {
      throw new UnauthorizedException(
        'You are not authorized to access this api endpoint',
      );
    }

    if (user.role === Role.ACCOUNT_MANAGER && params.organization) {
      // check if account manager is assigned a queried organization
      const isAssigned = this.userService.hasAccessToOrganization(
        user.userId,
        params.organization,
      );

      if (!isAssigned)
        throw new UnauthorizedException(
          'You are not authorized to perform action for this organization',
        );
    }

    return true;
  }
}


当我在roles gaurd中注入用户服务时,我开始在使用RolesGaurd的每个模块中得到这个错误:

Error: Nest can't resolve dependencies of the RolesGuard (Reflector, ?). Please make sure that the argument UserService at index [1] is available in the CoachModule context.

Potential solutions:
- Is CoachModule a valid NestJS module?
- If UserService is a provider, is it part of the current CoachModule?
- If UserService is exported from a separate @Module, is that module imported within CoachModule?
  @Module({
    imports: [ /* the Module containing UserService */ ]
  })


这个问题的解决方案是什么,这样我就不需要向使用RolesGaurd的每个模块添加用户服务导入

dtcbnfnu

dtcbnfnu1#

必须使该提供程序对使用RolesGuard防护的所有模块可用
所以你应该:
1.在每个将使用guard的模块中导入导出UserService的模块,或者
1.在根模块中导入导出UserService的全局模块,或者
1.在将使用该保护的每个模块中注册该提供程序

相关问题