All files composeMiddlewares.ts

100% Statements 17/17
100% Branches 4/4
100% Functions 3/3
100% Lines 17/17

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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41      8x 11x 1x     10x 13x 1x       9x     8x     14x 1x     13x   13x   13x 2x     11x   11x     8x      
import { UseCase } from '.';
import { Middleware, Context } from './interfaces';
 
export function composeMiddlewares(middlewares: Middleware[]) {
  if (!Array.isArray(middlewares)) {
    throw new TypeError('Middleware stack must be an array!');
  }
 
  for (const fn of middlewares) {
    if (typeof fn !== 'function') {
      throw new TypeError('Middleware must be composed of functions!');
    }
  }
 
  return async function runStack<D, A extends UseCase, R>(
    context: Context<D, A, R>,
  ): Promise<unknown> {
    let index = -1;
 
    async function next(i: number): Promise<unknown> {
      if (i <= index) {
        throw new Error('next() called multiple times');
      }
 
      index = i;
 
      let currentMiddleware = middlewares[i];
 
      if (i === middlewares.length) {
        return Promise.resolve();
      }
 
      const nextMiddlewareNext = next.bind(null, i + 1);
 
      return await currentMiddleware(context, nextMiddlewareNext);
    }
 
    return await next(0);
  };
}