如果不允许调用程序,则阻止TypeScript中方法的调用



我创建了一个装饰器,用于查找方法调用方的名称,并与"允许的"调用方列表匹配

我的目标是只在一个地方保持方法的实施

所以我想知道,做这样的东西是正确的吗?我还没有试过生产,这会引起问题吗?有可能改进它,如果是,如何改进?

谢谢!

代码或StackBlitz:

function protectMethod(allowedCaller: string[]) {
return function(target, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
/**
* callerName by Iris Li
* https://gist.github.com/irisli/716b6dacd3f151ce2b7e
*/
var stackTrace = new Error().stack; // Only tested in latest FF and Chrome
var callerName = stackTrace.replace(/^Errors+/, ""); // Sanitize Chrome
callerName = callerName.split("n")[1].trim(); // 1st item is this, 2nd item is caller
callerName = callerName.replace(/^s+at Object./, ""); // Sanitize Chrome
callerName = callerName.replace(/ (.+)$/, ""); // Sanitize Chrome
if (callerName.slice(0, 3) == "at ") callerName = callerName.slice(3); // Sanitize Chrome
callerName = callerName.replace(/@.+/, ""); // Sanitize Firefox
const allowed = allowedCaller.filter(e => {
return e === callerName;
});
if (!allowed.length) {
console.warn(`Caller "${callerName}" should not call "${propertyKey}"`);
}
originalMethod.apply(this, args);
};
};
}
class Class1 {
search: Class2 = new Class2()
call_method() {
this.search.method_service(true);
}
}
class Class2 {
constructor() {}
@protectMethod(["Class1.call_method"])
method_service(v) {
console.log("service called ", v);
}
}

堆栈属性不是标准的,不应在生产中使用

对不起,我没有其他方法。

最新更新