Skip to content

Commit

Permalink
fix: calling decorated method with array of keys
Browse files Browse the repository at this point in the history
  • Loading branch information
onhate committed Sep 7, 2023
1 parent 0586002 commit 1f0b9e2
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "inbatches",
"version": "0.0.9",
"version": "0.0.10",
"private": false,
"license": "MIT",
"repository": {
Expand Down
23 changes: 23 additions & 0 deletions src/decorator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ class RunInBatches {
}

async getAll(keys: string): Promise<string>;
async getAll(keys: string[]): Promise<string[]>;

@InBatches()
async getAll(keys: string | string[]): Promise<string | string[]> {
Expand Down Expand Up @@ -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');
});
});
3 changes: 3 additions & 0 deletions src/decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ export function InBatches<K, V>(options?: BatcherOptions) {
const method = descriptor.value;
descriptor.value = function (key: K) {
const batcher = getInstanceBatcher<any, K, V>(this, property, method, options);
if (Array.isArray(key)) {
return Promise.all(key.map(each => batcher.enqueue(each)));
}
return batcher.enqueue(key);
};

Expand Down

0 comments on commit 1f0b9e2

Please sign in to comment.