Skip to content

Commit 1f0b9e2

Browse files
committed
fix: calling decorated method with array of keys
1 parent 0586002 commit 1f0b9e2

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "inbatches",
3-
"version": "0.0.9",
3+
"version": "0.0.10",
44
"private": false,
55
"license": "MIT",
66
"repository": {

src/decorator.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ class RunInBatches {
55
}
66

77
async getAll(keys: string): Promise<string>;
8+
async getAll(keys: string[]): Promise<string[]>;
89

910
@InBatches()
1011
async getAll(keys: string | string[]): Promise<string | string[]> {
@@ -66,4 +67,26 @@ describe('Batch Decorator', () => {
6667
const values = await Promise.all(promises);
6768
expect(values).toEqual(['batch1.1-index-0-i1', 'batch1.2-index-1-i1', 'batch2-index-0-i1']);
6869
});
70+
71+
it('should also work when passing array of keys to batch enabled method', async () => {
72+
const runner = new RunInBatches('i1');
73+
74+
const values = await runner.getAll(['a', 'b', 'c']);
75+
expect(values).toEqual(['a-index-0-i1', 'b-index-1-i1', 'c-index-2-i1']);
76+
});
77+
78+
it('should also work when passing array of keys to batch enabled method (multiple batches)', async () => {
79+
const runner = new RunInBatches('i1');
80+
81+
const keys = Array.from({ length: 50 }, (_, i) => 'key-' + i);
82+
const values = await runner.getAll(keys);
83+
84+
expect(values).toHaveLength(50);
85+
// batch 1 of 25 items
86+
expect(values).toContain('key-0-index-0-i1');
87+
expect(values).toContain('key-24-index-24-i1');
88+
// batch 2 of 25 items
89+
expect(values).toContain('key-25-index-0-i1');
90+
expect(values).toContain('key-49-index-24-i1');
91+
});
6992
});

src/decorator.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ export function InBatches<K, V>(options?: BatcherOptions) {
3838
const method = descriptor.value;
3939
descriptor.value = function (key: K) {
4040
const batcher = getInstanceBatcher<any, K, V>(this, property, method, options);
41+
if (Array.isArray(key)) {
42+
return Promise.all(key.map(each => batcher.enqueue(each)));
43+
}
4144
return batcher.enqueue(key);
4245
};
4346

0 commit comments

Comments
 (0)