方法decorator应返回第一个执行结果Typescript



我有一个方法装饰器,它只允许执行一次装饰的方法。这个函数运行良好,但在我的第三次单元测试中失败了,因为它给出了未定义的结果,但应该返回第一个执行结果
这是我的装饰师:

import "reflect-metadata";
const metadataKey = Symbol("initialized");
function once(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const method = descriptor.value;
descriptor.value = function (...args) {
const initialized = Reflect.getMetadata(
metadataKey,
target,
propertyKey
);
if (initialized) {
return;
}
Reflect.defineMetadata(metadataKey, true, target, propertyKey);
method.apply(this, args);
};
}  

我认为问题在于if语句的返回,它应该返回一些东西,但idk是什么。我打了一点,但没有成功,这就是为什么我请求你的帮助
这些是单元测试:

describe('once', () => {
it('should call method once with single argument', () => {
class Test {
data: string;
@once
setData(newData: string) {
this.data = newData;
}
}
const test = new Test();
test.setData('first string');
test.setData('second string');
assert.strictEqual(test.data, 'first string')
});
it('should call method once with multiple arguments', () => {
class Test {
user: {name: string, age: number};
@once
setUser(name: string, age: number) {
this.user = {name, age};
}
}
const test = new Test();
test.setUser('John',22);
test.setUser('Bill',34);
assert.deepStrictEqual(test.user, {name: 'John', age: 22})
});
it('should return always return first execution result', () => {
class Test {
@once
sayHello(name: string) {
return `Hello ${name}!`;
}
}
const test = new Test();
test.sayHello('John');
test.sayHello('Mark');
assert.strictEqual(test.sayHello('new name'), 'Hello John!')
})
}); 

提前感谢!

这个装饰器基本上是进行内存化的,但方法调用的结果不会存储在任何地方。这就是缺失的东西。

我的建议是添加另一个名为result之类的元数据:

const meta = Reflect.getMetadata(...);
if (meta?.initialized) return meta.result;
const result = method.apply(this, args);
const newMeta = { initialized: true, result };
Reflect.defineMetadata(metadataKey, newMeta, target, propertyKey);

最新更新