From c91481fa8cd8b94c5924869a1fc4a8b0b6c70ae3 Mon Sep 17 00:00:00 2001 From: Masoud Salehi Date: Sun, 4 Aug 2024 13:43:20 +0330 Subject: [PATCH] fix(delegate): Fix default serialization with many args --- package-lock.json | 2 +- src/delegate/delegate.spec.ts | 24 ++++++++++++++++++++++++ src/delegate/delegatify.ts | 2 +- 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index d5bb84b..48270ce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,7 +6,7 @@ "packages": { "": { "name": "utils-decorators", - "version": "2.0.6", + "version": "2.0.7", "license": "MIT", "dependencies": { "tinyqueue": "^2.0.3" diff --git a/src/delegate/delegate.spec.ts b/src/delegate/delegate.spec.ts index 21f3dfe..8deabdc 100644 --- a/src/delegate/delegate.spec.ts +++ b/src/delegate/delegate.spec.ts @@ -95,6 +95,30 @@ describe('delegate', () => { expect(counter).toEqual(2); }); + it('should delegate method with same key invocation - default key serialization - many args', async () => { + let counter = 0; + + class T { + @delegate() + async foo(...args: number[]): Promise { + counter += 1; + await sleep(20); + + return Promise.resolve(args.reduce((a, b) => a + b)); + } + } + + const t = new T(); + + const res = await Promise.all([ + t.foo(1, 1, 1, 1), + t.foo(1, 1, 1, 2), + t.foo(1, 1, 1, 1), + ]); + expect(res).toEqual([4, 5, 4]); + expect(counter).toEqual(2); + }); + it('should delegate method with same key invocation - custom serialization', async () => { let counter = 0; diff --git a/src/delegate/delegatify.ts b/src/delegate/delegatify.ts index 4e4fdda..26f0788 100644 --- a/src/delegate/delegatify.ts +++ b/src/delegate/delegatify.ts @@ -5,7 +5,7 @@ export function delegatify( keyResolver?: (...args: A) => string, ): AsyncMethod { const delegatedKeysMap = new Map>(); - const keyGenerator: (...args: any[]) => string = keyResolver ?? JSON.stringify; + const keyGenerator: (...args: any[]) => string = keyResolver ?? ((...args) => JSON.stringify(args)); return function (...args: A): Promise { const key = keyGenerator(...args);