1- # InBatches (📦📦📦 )
1+ # @ InBatches (📦,📦,📦,... )
22
3- InBatches is a zero-dependency TypeScript library that provides a convenient way to batch and execute asynchronous
4- operations in a controlled manner. This library is especially useful for scenarios where you need to perform multiple
5- asynchronous operations efficiently, such as when making network requests or performing database queries.
3+ InBatches is a zero-dependency generic TypeScript library that provides a convenient way to batch executions that runs
4+ asynchronous.
65
7- Heavily inspired by [ graphql/dataloader] ( https://github.com/graphql/dataloader ) but better 😜
6+ It is designed to be used as part of your application's data fetching layer to provide a consistent API over various
7+ backends and reduce requests to those backends via batching.
8+
9+ This library is especially useful for scenarios where you need to perform multiple asynchronous operations efficiently,
10+ such as when making network requests or performing database queries.
11+
12+ Heavily inspired by [ graphql/dataloader] ( https://github.com/graphql/dataloader ) but using classes and decorators 😜
813
914## Table of Contents
1015
@@ -27,12 +32,13 @@ npm install inbatches
2732
2833## Usage
2934
30- ### Basic Usage
35+ ### Using the ` Batcher ` Class
3136
3237``` typescript
3338import { Batcher } from ' inbatches' ;
3439
3540// Define a class that extends Batcher and implements the `run` method
41+ // the `run` method will be called with an array of keys collected from the `enqueue` method
3642class MyBatcher extends Batcher <number , string > {
3743 async run(ids : number []): Promise <string []> {
3844 // Perform asynchronous operations using the keys
@@ -44,16 +50,14 @@ class MyBatcher extends Batcher<number, string> {
4450// Create an instance of your batcher
4551const batcher = new MyBatcher ();
4652
47- // Enqueue keys for batching and execution
48- const resultPromise1 = batcher .enqueue (1 );
49- const resultPromise2 = batcher .enqueue (2 );
50-
51- resultPromise1 .then (result => {
52- console .log (result ); // Output: "{ id: 1, name: 'Result for key 1' }"
53+ // Enqueue keys for batched execution
54+ const result = [1 , 2 , 3 , 4 , 5 ].map (async id => {
55+ return await batcher .enqueue (id );
5356});
5457
55- resultPromise2 .then (result => {
56- console .log (result ); // Output: "{ id: 2, name: 'Result for key 2' }"
58+ // The result will be an array of results in the same order as the keys
59+ result .then (results => {
60+ console .log (results ); // Output: [{ id: 1, name: 'Result for key 1' }, ...]
5761});
5862```
5963
@@ -65,10 +69,13 @@ The library also provides a decorator called `InBatches` that you can use to bat
6569import { InBatches } from ' inbatches' ;
6670
6771class MyService {
68- @InBatches ()
72+
73+ // (optional) overloaded method, where you define the keys as `number` and the return type as `string` for typings
74+ async fetch(keys : number ): Promise <string >;
75+
76+ // in reality the Decorator will wrap this method and it will never be called with a single key :)
77+ @InBatches () // This method is now batch-enabled
6978 async fetch(keys : number | number []): Promise <string | string []> {
70- // This method is now batch-enabled
71- // Perform asynchronous operations using the keys
7279 if (Array .isArray (keys )) {
7380 return this .db .getMany (keys );
7481 }
@@ -80,16 +87,13 @@ class MyService {
8087
8188const service = new MyService ();
8289
83- // Enqueue keys for batching and execution
84- const resultPromise1 = service .fetch (1 );
85- const resultPromise2 = service .fetch (2 );
86-
87- resultPromise1 .then (results => {
88- console .log (results ); // Output: { id: 1, name: 'Result for key 1' }
90+ const result = [1 , 2 , 3 , 4 , 5 ].map (async id => {
91+ return await service .fetch (id );
8992});
9093
91- resultPromise2 .then (results => {
92- console .log (results ); // Output: { id: 2, name: 'Result for key 2' }
94+ // The result will be an array of results in the same order as the keys
95+ result .then (results => {
96+ console .log (results ); // Output: [{ id: 1, name: 'Result for key 1' }, ...]
9397});
9498```
9599
@@ -100,7 +104,9 @@ resultPromise2.then(results => {
100104An interface to specify options for the batcher.
101105
102106- ` maxBatchSize ` : The maximum number of keys to batch together. Default is ` 25 ` .
103- - ` delayWindowInMs ` : The delay window in milliseconds before dispatching the batch. Default is ` undefined ` .
107+ - ` delayWindowInMs ` : (not recommended) The delay window in milliseconds before dispatching the batch. Default
108+ is ` undefined ` and will use ` process.nextTick ` to dispatch the batch, which is highly efficient and fast. Only use
109+ this if you really want to accumulate promises calls in a window of time before dispatching the batch.
104110
105111### ` Batcher<K, V> ` Class
106112
@@ -116,15 +122,19 @@ A decorator function that can be applied to methods to enable batching.
116122- Usage: ` @InBatches(options?: BatcherOptions) `
117123- Example:
118124
119- ``` typescript
120- class MyService {
121- @InBatches ({ maxBatchSize: 10 })
122- async fetchResults(keys : number | number []): Promise <string | string []> {
123- // Batch-enabled method logic
124- }
125- }
126- ```
125+ ``` typescript
126+ class MyService {
127127
128+ // (optional) overloaded method, where you define the keys as `number` and the return type as `string` for typings
129+ async fetchResults(keys : number ): Promise <string >
130+
131+ @InBatches ({ maxBatchSize: 10 })
132+ async fetchResults(keys : number | number []): Promise <string | string []> {
133+ // Batch-enabled method logic
134+ }
135+ }
136+ ```
137+
128138## Contributing
129139
130140Contributions are welcome! Feel free to open issues or submit pull requests on
0 commit comments