【问题标题】:Is it possible to pass a parameter to a nestjs guard?是否可以将参数传递给nestjs警卫?
【发布时间】:2020-09-14 16:31:54
【问题描述】:

我正在尝试提出一个可重用的守卫,看起来我需要将字符串参数传递给守卫。在nestjs中可以实现吗?

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    听起来您正在寻找使用mixin,这是一个返回类的函数。我不确定你传递什么样的参数,但想法是

    export const RoleGuard = (role: string) => {
      class RoleGuardMixin implements CanActivate {
        canActivate(context: ExecutionContext) {
          // do something with context and role
          return true;
        }
      }
    
      const guard = mixin(RoleGuardMixin);
      return guard;
    }
    

    mixin 作为函数是从@nestjs/common 导入的,是一个将@Injectable() 装饰器应用于类的包装函数

    现在要使用守卫,你需要做类似@UseGuards(RoleGuard('admin'))

    【讨论】:

    • @SimonSchürg 查看确定问题所需的代码。我已经多次使用这种模式,没有失败。
    • @JayMcDoniel 我已经在我的嵌套 js 代码中找出了异常问题。令我惊讶的是,它与 mixin 保护模式无关。原因是我在一个控制器中错误地使用了防护装置。很抱歉没有相关的评论。我删除了它以避免混淆。
    • @JayMcDoniel 但如果没有 mixin 或使用 @UseGuards(new PermissionsGuard2('test'))
    • @Michael 如果您有新问题,最好创建一个新帖子。从您的评论中,我不知道这里问的是什么
    【解决方案2】:

    在 NestJs 的 Guard 中使用 mixin 似乎是不可能的。它将抛出导出的变量“RoleGuard”已经或正在使用私有名称“RoleGuardMixin”。

    其实你可以使用 setMetadata 将参数一一传入,然后使用来自 '@nestjs/core' 的反射器从 Guard 中获取。

        @Injectable()
        export class RoleGuard implements CanActivate {
            constructor(
                private reflector: Reflector,
            ) {}
    
            canActivate(context: ExecutionContext) {
              const roleName = this.reflector.get<string>('roleName', context.getHandler());
              return true;
            }
        }
    
        @Get()
        @SetMetadata('roleName', 'developer')
        async testRoleGuard() {
          return true;
        }
    

    或者你可以定义一个装饰器来传递参数。

    export const RoleName = (roleName: string) => SetMetadata('roleName', roleName);
    
        @Get()
        @RoleName('developer')
        async testRoleGuard() {
          return true;
        }
    

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 1970-01-01
      • 2011-04-22
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      • 2010-09-15
      相关资源
      最近更新 更多