Code coverage report for core/src/decorators/join.ts

Statements: 22.73% (5 / 22)      Branches: 28.57% (2 / 7)      Functions: 25% (1 / 4)      Lines: 23.81% (5 / 21)      Ignored: none     

All files » core/src/decorators/ » join.ts
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    1 1 1 1                                             1                                
import {Filter} from './filters';
 
export enum Join {
  BEFORE,
  AFTER,
  ERROR,
}
 
export type JoinOptions = {
  target: unknown;
  filter?: Filter;
  join: Join;
  original: (...args: unknown[]) => unknown;
  execute: (err?: unknown, result?: unknown) => void;
}
 
function joinError(options: JoinOptions, ...args: unknown[]): any {
  try {
    const result = options.original.apply(options.target, args);
    if (result instanceof Promise) {
      result.catch(err => options.execute(err));
    }
    return result;
  } catch (err) {
    options.execute(err);
  }
}
 
export function wrapJoin(options: JoinOptions, ...args: unknown[]): any {
  let result: unknown;
  switch (options.join) {
    case Join.AFTER:
      result = options.original.apply(options.target, args);
      options.execute(undefined, result);
      break;
    case Join.BEFORE:
      options.execute();
      result = options.original.apply(options.target, args);
      break;
    case Join.ERROR:
      result = joinError(options);
      break;
  }
  return result;
}