【问题标题】:Guard factory in nestJS applicationNestJS 应用程序中的守​​卫工厂
【发布时间】:2020-11-20 10:35:31
【问题描述】:

我正在尝试创建一个 guard 工厂,以便根据给定的参数创建一个守卫,但遇到了问题。

我建了以下工厂

@Injectable()
export class GateKeeperFactory {
  public static guards = []

  static forRoute(allow: boolean) {
    @Injectable()
    class GateKeeperCustomGuard implements CanActivate {
      canActivate(context: ExecutionContext): boolean {
        return allow
      }
    }
    const result = GateKeeperCustomGuard
    GateKeeperFactory.guards.push(result)
    return result
  }
}

并将以下内容添加到我的app.module.ts

  providers: [GateKeeperFactory, ...GateKeeperFactory.guards],

为了测试这一点,我创建了以下控制器

@Controller('/test1')
export class Test1Controller {
  @Get('1')
  @UseGuards(GateKeeperFactory.forRoute(false))
  test1() {
    return { in: true }
  }

  @Get('2')
  @UseGuards(GateKeeperFactory.forRoute(true))
  test2() {
    return { in: true }
  }
}

@UseGuards(GateKeeperFactory.forRoute(false))
@Controller('/test2')
export class Test2Controller {
  @Get('1')
  test1() {
    return { in: true }
  }
}

问题是所有 3 条路线都被阻止或所有 3 条路线都未被阻止 我可以假设 allow 参数由于某种原因在守卫之间共享,我错过了(我验证创建了 3 个不同的守卫)


注 1: 根据guide,我知道他们提供了一种通过使用SetMetadata 将参数传递给警卫的不同方法,此时我想避免


注2: 尝试向守卫添加构造函数并将它们用作实例会导致错误:[ExceptionHandler] metatype is not a constructor 加载服务器时

【问题讨论】:

    标签: typescript nestjs


    【解决方案1】:

    听起来你真正想要的是所谓的mixin,一个返回一个类的函数,该闭包允许类使用mixin的参数。这就是 Nest 创建它的 Passport AuthGuard() 的方式,顺便说一句。要从上面的示例中获取并稍微调整一下,您可以执行以下操作:

    import { CanActivate, ExecutionContext, mixin } from '@nestjs/common';
    
    export function GateKeeper(allow: boolean) {
      
      class GateKeeperCustomGuard implements CanActivate {
        canActivate(context: ExecutionContext): boolean {
          return allow
        }
      }
    
      return mixin(GateKeeperCustomGuard) as CanActivate;
    }
    

    现在你应该可以使用像@UseGuards(GateKeeper(true))这样的守卫了

    【讨论】:

    • 我用这种方法得到[ExceptionHandler] metatype is not a constructor
    猜你喜欢
    • 2020-05-29
    • 1970-01-01
    • 2022-08-11
    • 2023-03-16
    • 1970-01-01
    • 2021-02-03
    • 2019-09-14
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多