【发布时间】: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