# All files / domains/hooks registry.ts

86.67% Statements 13/15
75% Branches 6/8
100% Functions 2/2
86.67% Lines 13/15

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
    6320x
    20x
    20x
    20x
    20x

    5x

    5x
    5x

    20x

    3x

    3x
    3x

    20x

     import { GraphQLResolveInfo } from 'graphql';
    import { DeepWeakMap } from '~/services/utils';
    import { HookError } from './error';

    export interface HookExecutorResolverArgs {
      source: any;
      arIgs: { [argName: string]: any };
      context: any;
      info: GraphQLResolveInfo;
    }

    export type HookExecutor<Result = void> = (
      data: HookExecutorResolverArgs,
    ) => Result | Promise<Result>;
    I
    export interface AllRegisteredHooks {
      [fieldName: string]: HookExecutor;
    }

    export const fieldBeforeHooksRegistry = new DeepWeakMap<
      Function,
      HookExecutor[],
      AllRegisteredHooks
    >();

    export const fieldAfterHooksRegistry = new DeepWeakMap<
      Function,
      HookExecutor[],
      AllRegisteredHooks
    >();

    export function registerFieldBeforeHook(
      target: Function,
      fieldName: string,
      hook: HookExecutor,
    ) {
      if (!hook) {
        throw new HookError(
          target,
          fieldName,
          `Field @Before hook function must be supplied.`,
        );
      }
      const currentHooks = fieldBeforeHooksRegistry.get(target, fieldName) || [];
      fieldBeforeHooksRegistry.set(target, fieldName, [hook, ...currentHooks]);
    }

    export function registerFieldAfterHook(
      target: Function,
      fieldName: string,
      hook: HookExecutor,
    ) {
      if (!hook) {
        throw new HookError(
          target,
          fieldName,
          `Field @After hook function must be supplied.`,
        );
      }
      const currentHooks = fieldAfterHooksRegistry.get(target, fieldName) || [];
      fieldAfterHooksRegistry.set(target, fieldName, [hook, ...currentHooks]);
    }