Tengo un decorador de métodos que permite ejecutar un método decorado solo una vez. Esta función funciona bien, pero en mi prueba de la tercera unidad falla porque da un resultado indefinido pero debería devolver el primer resultado de ejecución.
Este es mi decorador:
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); }; } Creo que el problema está en el retorno de la instrucción if, debería devolver algo, pero no sé qué. Jugué un poco pero no tuve éxito, por eso les pido ayuda.
Estas son las pruebas unitarias:
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!') }) });¡Gracias por adelantado!
Este decorador básicamente memoriza, pero el resultado de la llamada al método no se almacena en ninguna parte. Esto es lo que falta.
Mi sugerencia sería agregar otra pieza de metadatos llamada result o algo así:
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);