【发布时间】:2020-09-14 16:31:54
【问题描述】:
我正在尝试提出一个可重用的守卫,看起来我需要将字符串参数传递给守卫。在nestjs中可以实现吗?
【问题讨论】:
标签: nestjs
我正在尝试提出一个可重用的守卫,看起来我需要将字符串参数传递给守卫。在nestjs中可以实现吗?
【问题讨论】:
标签: nestjs
听起来您正在寻找使用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'))
【讨论】:
在 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;
}
【讨论】: