All files concurrencyDecorator.ts

100% Statements 13/13
100% Branches 4/4
100% Functions 4/4
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25  1x 1x 1x   1x             135x 135x 909x 909x 135x 909x 136x 909x          
import {concurrency as _concurrency} from './concurrency';
 
/* tslint:disable no-invalid-this */
 
const instances = new WeakMap<any, WeakMap<any, any>>();
 
/**
 * A class method decorator that limits the concurrency of the method to the
 * given number of parallel executions. All invocations are queued and executed
 * in the order they were called.
 */
export function concurrency<This, Args extends any[], Return>(limit: number) {
  return (
    fn: (this: This, ...args: Args) => Promise<Return>,
    context?: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Promise<Return>>,
  ) => {
    return async function (this: This, ...args: Args): Promise<Return> {
      let map = instances.get(this);
      if (!map) instances.set(this, (map = new WeakMap<any, any>()));
      if (!map.has(fn)) map.set(fn, _concurrency(limit));
      return map.get(fn)!(async () => await fn.call(this, ...args));
    };
  };
}