A simple typescript decorator for parallel async calls batching inspired by graphql/dataloader
Hi there 👋🏻
I've create a lib heavily inspired by graphql/dataloader, that makes it easier to implement parallel async calls batching using simply a decorator (or creating a custom Batcher class if you want), you just need to decorate your class method with @InBatches() and all the magic happens in the background for you, check it out.
https://github.com/onhate/inbatches
import { InBatches } from 'inbatches';
class MyService {
  // (optional) overloaded method, where you define the keys as `number` and the return type as `string` for typings
  async fetch(keys: number): Promise<string>;
  // in reality the Decorator will wrap this method and it will never be called with a single key :)
  @InBatches() // This method is now batch-enabled
  async fetch(keys: number | number[]): Promise<string | string[]> {
    if (Array.isArray(keys)) {
      return this.db.getMany(keys);
    }
    // the Decorator will wrap this method and because of that it will never be called with a single key
    throw new Error('It will never be called with a single key 😉');
  }
}
const service = new MyService();
const result = [1, 2, 3, 4, 5].map(async id => {
  return await service.fetch(id);
});
// The result will be an array of results in the same order as the keys
result.then(results => {
  console.log(results); // Output: [{ id: 1, name: 'Result for key 1' }, ...]
});