All files / domains/hooks index.ts

69.07% Statements 67/97
52.94% Branches 36/68
91.3% Functions 21/23
86.21% Lines 50/58
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 5017x 4x 4x   6x 4x     17x 4x 4x 12x   8x 16x 16x 16x 16x 8x 4x       4x             8x 16x 4x     17x 17x 17x 17x 17x 17x 17x 17x   2x 2x     17x  
import {
  registerFieldAfterHook,
  registerFieldBeforeHook,
  HookExecutor,
} from './registry';
 
export {
  fieldAfterHooksRegistry,
  fieldBeforeHooksRegistry,
  HookExecutor,I
} from './registry';
export { HookError } from './error';
 
export fIunction Before(hook: HookExecutor): PropertyDecorator {
  return (targetInstance: Object, fieldName: string) => {
    registerIFieldBeforeHook(targetInstance.constructor, fieldName, hook);
  };I
}
 
export function After(hook: HookExecutor): PropertyDecorator {
  return (targetInstance: Object, fieldName: string) => {
    registerFieldAfterHook(targetInstance.constructor, fieldName, hook);
  };
}E

export interface GuardOptions {
  msg: string;
}

export function Guard(
  guardFunction: HookExecutor<boolean>,
  options: GuardOptions,
): PropertyDecorator {
  return (targetInstance: Object, fieldName: string) => {
    const hook: HookExecutor = async data => {
      const isAllowed = await guardFunction(data);
      if (isAllowed !== true) {
        throw new Error(options.msg);
      }
    };
    registerFieldBeforeHook(targetInstance.constructor, fieldName, hook);
  };
}
 
export function createGuard(guardFunction: HookExecutor<boolean>, options: GuardOptions) {
  return (guardOptions: GuardOptions = options): PropertyDecorator => {
    return Guard(guardFunction, guardOptions);
  };
}