From 1f0b9e26661496856a969767dd0600accb453ddd Mon Sep 17 00:00:00 2001 From: Marcelo Luiz Onhate Date: Thu, 7 Sep 2023 12:59:11 -0300 Subject: [PATCH] fix: calling decorated method with array of keys --- package.json | 2 +- src/decorator.spec.ts | 23 +++++++++++++++++++++++ src/decorator.ts | 3 +++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 21787cd..6428aad 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "inbatches", - "version": "0.0.9", + "version": "0.0.10", "private": false, "license": "MIT", "repository": { diff --git a/src/decorator.spec.ts b/src/decorator.spec.ts index 585d32e..46380e8 100644 --- a/src/decorator.spec.ts +++ b/src/decorator.spec.ts @@ -5,6 +5,7 @@ class RunInBatches { } async getAll(keys: string): Promise; + async getAll(keys: string[]): Promise; @InBatches() async getAll(keys: string | string[]): Promise { @@ -66,4 +67,26 @@ describe('Batch Decorator', () => { const values = await Promise.all(promises); expect(values).toEqual(['batch1.1-index-0-i1', 'batch1.2-index-1-i1', 'batch2-index-0-i1']); }); + + it('should also work when passing array of keys to batch enabled method', async () => { + const runner = new RunInBatches('i1'); + + const values = await runner.getAll(['a', 'b', 'c']); + expect(values).toEqual(['a-index-0-i1', 'b-index-1-i1', 'c-index-2-i1']); + }); + + it('should also work when passing array of keys to batch enabled method (multiple batches)', async () => { + const runner = new RunInBatches('i1'); + + const keys = Array.from({ length: 50 }, (_, i) => 'key-' + i); + const values = await runner.getAll(keys); + + expect(values).toHaveLength(50); + // batch 1 of 25 items + expect(values).toContain('key-0-index-0-i1'); + expect(values).toContain('key-24-index-24-i1'); + // batch 2 of 25 items + expect(values).toContain('key-25-index-0-i1'); + expect(values).toContain('key-49-index-24-i1'); + }); }); diff --git a/src/decorator.ts b/src/decorator.ts index cec4ce2..12b18ac 100644 --- a/src/decorator.ts +++ b/src/decorator.ts @@ -38,6 +38,9 @@ export function InBatches(options?: BatcherOptions) { const method = descriptor.value; descriptor.value = function (key: K) { const batcher = getInstanceBatcher(this, property, method, options); + if (Array.isArray(key)) { + return Promise.all(key.map(each => batcher.enqueue(each))); + } return batcher.enqueue(key); };