All files createApp.ts

100% Statements 20/20
100% Branches 5/5
100% Functions 7/7
100% Lines 20/20

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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159  7x                                                                                                                                                                                                         7x 9x     12x 1x     11x     9x   2x   2x           10x       8x   12x 12x     12x         8x   8x           8x   4x 1x         3x        
import { UseCase, UseCaseType } from '.';
import { composeMiddlewares } from './composeMiddlewares';
 
import { Context, Middleware } from './interfaces';
/**
 * A DYAL app
 * @example
 * ```typescript
 * const app = createApp(dependencies);
 * const commandBus: CommandBus = createCommandBus();
 * commandBus.register('CountCommand', countCommandHandler);
 * app.on('command').use(commandBus.middleware);
 *
 * export interface CountCommandResult {
 *   total: number;
 * }
 *
 * const countCommand: CountCommand = {
 *   type: 'command',
 *   name: 'CountCommand',
 *   payload: {
 *    count: 5,
 *   },
 * };
 *
 * const result = await app.execute<CountCommandResult>(countCommand);
 * ```
 */
export interface DyalApp {
  /**
   *
   * @param target It's the kind of use case your middleware will be called for. Can be `query`, `command` or `all`
   * @example
   * ```typescript
   * app.on('command').use(commandHandlerMiddleware);
   * ```
   */
  on(target: UseCaseType): {
    /**
     *
     * @param middleware middleware to add to the app stack
     * @returns void
     * @example
     * ```typescript
     * app.on('all').use(middleware);
     * ```
     */
    use(middleware: Middleware): void;
  };
 
  /**
   *
   * @param middleware middleware to add to the app stack
   * @returns void
   * @example
   * ```typescript
   * app.use(middleware);
   * ```
   */
  use(middleware: Middleware): void;
 
  /**
   * @param useCase The useCase to execute.
   * @type R The useCase's return type.
   * @returns R
   * @example
   * ```typescript
   * const app = createApp(dependencies);
   * const commandBus: CommandBus = createCommandBus();
   * commandBus.register('CountCommand', countCommandHandler);
   * app.on('command').use(commandBus.middleware);
   *
   * export interface CountCommandResult {
   *   total: number;
   * }
   *
   * const countCommand: CountCommand = {
   *   type: 'command',
   *   name: 'CountCommand',
   *   payload: {
   *    count: 5,
   *   },
   * };
   *
   * const result = await app.execute<CountCommandResult>(countCommand);
   * ```
   */
  execute<R>(useCase: UseCase): Promise<R>;
}
 
/**
 * @param dependencies Your app dependencies like repositories, logger, database connection, etc...
 * @returns CQRSApp
 * @example
 * ```typescript
 * const dependencies: AppDependencies = { logger: console.log };
 * const app = createApp(dependencies);
 * app.use(loggerMiddleware);
 * const commandResult = await app.execute(commands);
 * const queryResult = await app.execute(query);
 * ```
 */
export function createApp<D>(dependencies: D): DyalApp {
  const middlewares: { target: UseCaseType; middleware: Middleware }[] = [];
 
  function use(target: UseCaseType, middleware: Middleware) {
    if (typeof middleware !== 'function') {
      throw new TypeError('Middleware must be composed of functions');
    }
 
    middlewares.push({ target, middleware });
  }
 
  return {
    on: (target: UseCaseType) => {
      return {
        use: (middleware: Middleware) => {
          use(target, middleware);
        },
      };
    },
 
    use: (middleware: Middleware) => {
      use('all', middleware);
    },
 
    execute: async <R>(useCase: UseCase): Promise<R> => {
      const targetMiddlewares = middlewares.reduce(
        (selectedMids: Middleware[], mid) => {
          if (mid.target === 'all' || mid.target === useCase.type) {
            selectedMids.push(mid.middleware);
          }
 
          return selectedMids;
        },
        [],
      );
 
      const midStack = composeMiddlewares(targetMiddlewares);
 
      const context: Context<D, UseCase, R> = {
        dependencies,
        useCase,
        result: undefined,
      };
 
      await midStack(context);
 
      if (!context.result) {
        throw new RangeError(
          'No result to return. At least one middleware must write the ctx.result object',
        );
      }
 
      return context.result;
    },
  };
}