如何解决如何使用类装饰器将装饰器应用于所有类方法
我正在使用实验性的打字稿装饰器来管理Express中的访问控制。
class AccountController extends Controller {
login(req: Request,res: Response) {
const { email,password } = req.body;
const token = await this.model.login(email,password);
return res.json({
token
});
}
@hasRole('ADMIN')
list(req: Request,res: Response) {
res.json({
data: await this.model.findAll()
});
}
}
hasRole
方法修饰器工作正常,我对此感到满意。
Controller
实现REST方法:
class Controller {
list(req: Request,res: Response) { // impl }
get(req: Request,res: Response) { // impl }
create(req: Request,res: Response) { // impl }
update(req: Request,res: Response) { // impl }
delete(req: Request,res: Response) { // impl }
}
问题是,我必须将相同的装饰器应用于大多数其他控制器,并且我发现它非常重复。例如,StockController
应该只允许访问MERCHANT
角色,而我必须执行以下操作:
class StockController extends Controller {
@hasRole('MERCHANT')
list(req: Request,res: Response) {
return super.list(req,res);
}
@hasRole('MERCHANT')
get(req: Request,res: Response) {
return super.get(req,res);
}
@hasRole('MERCHANT')
create(req: Request,res: Response) {
return super.create(req,res);
}
@hasRole('MERCHANT')
update(req: Request,res: Response) {
return super.update(req,res);
}
@hasRole('MERCHANT')
delete(req: Request,res: Response) {
return super.delete(req,res);
}
}
这种方法不仅笨拙且重复,而且不安全,因为如果我在Controller
中添加了一个方法而无意间忘记将该方法添加到子控制器中,则它们将允许不必要的访问。
我想使用类装饰器解决此问题,并使用类似以下的内容:
@requireRole('MERCHANT')
class StockController extends Controller {}
但是,根据我在doc中看到的内容:
类装饰器应用于类的构造函数,可用于观察,修改或替换类定义。
据我了解,我无法在类装饰器中实现“方法挂钩”。有什么建议吗?
供您参考,hasRole
装饰器如下所示:
export function hasRole(role: string) {
return function(target: Object,propertyKey: string,descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(req: Request,res: Response) {
const user = res.locals.user;
if (user && user.hasRole(role)) {
originalMethod.apply(this,[req,res]);
} else {
res.status(403).json({});
}
}
}
}
解决方法
这可以通过重写类方法来实现
function AttachToAllClassDecorator<T>(someParam: string) {
return function(target: new (...params: any[]) => T) {
for (const key of Object.getOwnPropertyNames(target.prototype)) {
// maybe blacklist methods here
let descriptor = Object.getOwnPropertyDescriptor(target.prototype,key);
if (descriptor) {
descriptor = someDecorator(someParam)(key,descriptor);
Object.defineProperty(target.prototype,key,descriptor);
}
}
}
}
基本上遍历所有方法(可能在其周围添加一些逻辑以将某些方法列入白名单/黑名单),并使用包装了方法装饰器的新方法进行覆盖。
这是方法装饰器的基本示例。
function someDecorator(someParam: string): (methodName: string,descriptor: PropertyDescriptor) => PropertyDescriptor {
return (methodName: string,descriptor: PropertyDescriptor): PropertyDescriptor => {
let method = descriptor.value;
descriptor.value = function(...args: any[]) {
console.warn(`Here for descriptor ${methodName} with param ${someParam}`);
return method.apply(this,args);
}
return descriptor;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。