All files / src/hooks hooks.ts

100% Statements 38/38
96.55% Branches 28/29
100% Functions 17/17
100% Lines 38/38

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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303          133x                                                                                                                                               133x         133x     133x               739x         614x                           3379x 298x   301x                                           36187x 36187x 71842x 71842x 313x     36187x                                   2084x 2084x 5x                   310x   359x                                         473x 473x 473x     570x                                         9x 9x 16x   9x     11x                                         3929x                                 10x 10x                                   529x       482x 482x       4421x 1x   4420x      
/**
 * Hook names accepted by `addHook` (Sequelize v6). Model lifecycle hooks, `beforeConnect`, `afterConnect`, the sync
 * hooks (`beforeBulkSync`, `afterBulkSync`, `beforeSync`, `afterSync`), `beforeDefine` / `afterDefine` and the static
 * `beforeInit` / `afterInit` run; the other connection hooks and query / association hooks are accepted and not run yet.
 */
export const HOOK_TYPES = [
  'beforeValidate',
  'afterValidate',
  'validationFailed',
  'beforeCreate',
  'afterCreate',
  'beforeUpdate',
  'afterUpdate',
  'beforeSave',
  'afterSave',
  'beforeDestroy',
  'afterDestroy',
  'beforeRestore',
  'afterRestore',
  'beforeUpsert',
  'afterUpsert',
  'beforeBulkCreate',
  'afterBulkCreate',
  'beforeBulkUpdate',
  'afterBulkUpdate',
  'beforeBulkDestroy',
  'afterBulkDestroy',
  'beforeBulkRestore',
  'afterBulkRestore',
  'beforeFind',
  'beforeFindAfterExpandIncludeAll',
  'beforeFindAfterOptions',
  'afterFind',
  'beforeCount',
  'beforeConnect',
  'afterConnect',
  'beforeDisconnect',
  'afterDisconnect',
  'beforePoolAcquire',
  'afterPoolAcquire',
  'beforeQuery',
  'afterQuery',
  'beforeSync',
  'afterSync',
  'beforeBulkSync',
  'afterBulkSync',
  'beforeDefine',
  'afterDefine',
  'beforeInit',
  'afterInit',
  'beforeAssociate',
  'afterAssociate',
] as const;
 
/** One of {@link HOOK_TYPES}. */
export type HookType = (typeof HOOK_TYPES)[number];
 
/**
 * Hook function. May be async; its return value is ignored. Receives the model class as `this`.
 * Its parameters are `any`, so an unannotated callback (`Model.beforeFind((options) => ...)`) compiles as it does against the Sequelize v6 typings; annotate them for type checking.
 */
// oxlint-disable-next-line typescript/no-explicit-any -- `never[]` would type the parameters of unannotated callbacks as `never`.
export type HookFunction = (...args: any[]) => unknown;
 
/** Registered hook: a function, optionally named so it can be removed by name. */
export type Hook = Readonly<{
  /** Hook name, used by `removeHook`. */
  name?: string;
  /** Hook function. */
  fn: HookFunction;
}>;
 
/** Hooks passed in `init({ hooks })` / `define({ hooks })`: one function or a list per hook type. */
export type HooksOption = Partial<
  Readonly<Record<HookType, HookFunction | readonly HookFunction[]>>
>;
 
const PROXIES: Partial<Readonly<Record<HookType, readonly HookType[]>>> = {
  beforeSave: ['beforeUpdate', 'beforeCreate', 'beforeSave'],
  afterSave: ['afterUpdate', 'afterCreate', 'afterSave'],
};
 
const HOOK_SET: ReadonlySet<string> = new Set(HOOK_TYPES);
 
/** Result when no hook is registered: nothing to wait for, no promise chain to build. */
const NO_HOOKS_RAN: Promise<void> = Promise.resolve();
 
/**
 * Immutable registry of hooks by type: `add` and `remove` return a new registry, so a model or `Sequelize`
 * instance replaces its registry on change.
 */
export class HookRegistry {
  /** Registry without hooks. */
  static readonly EMPTY: HookRegistry = new HookRegistry(new Map());
 
  readonly #hooks: ReadonlyMap<HookType, readonly Hook[]>;
 
  private constructor(hooks: ReadonlyMap<HookType, readonly Hook[]>) {
    this.#hooks = hooks;
  }
 
  /**
   * Builds a registry from the `hooks` option.
   *
   * @param option - One function or a list per hook type.
   * @param base - Registry the hooks are added to.
   * @returns Registry with the hooks of `base`, then those of `option`.
   */
  static fromOption(
    option: HooksOption | undefined,
    base: HookRegistry = HookRegistry.EMPTY,
  ): HookRegistry {
    return Object.entries(option ?? {}).reduce<HookRegistry>(
      (registry, [type, value]) =>
        (Array.isArray(value) ? value : [value]).reduce<HookRegistry>(
          (next, fn: HookFunction) => next.add(type, fn),
          registry,
        ),
      base,
    );
  }
 
  /**
   * Runs hooks of `type` from each registry in order (model hooks first, then Sequelize-level hooks).
   *
   * @param registries - Registries in run order.
   * @param type - Hook type.
   * @param context - `this` of the hook functions.
   * @param args - Hook arguments.
   * @returns Resolves when all hooks finished.
   */
  static runAll(
    registries: readonly HookRegistry[],
    type: HookType,
    context: unknown,
    ...args: readonly unknown[]
  ): Promise<void> {
    const hooks: Hook[] = [];
    for (const registry of registries) {
      const own = registry.#hooks.get(type);
      if (own !== undefined) {
        hooks.push(...own);
      }
    }
    return hooks.length === 0 ? NO_HOOKS_RAN : HookRegistry.#runInOrder(hooks, context, args);
  }
 
  /**
   * Runs the hooks of `type` from each registry synchronously, for the hook types that run while a
   * model or an instance is being defined (`beforeDefine`, `afterDefine`, `beforeInit`, `afterInit`).
   *
   * @param registries - Registries in run order.
   * @param type - Hook type.
   * @param context - `this` of the hook functions.
   * @param args - Hook arguments.
   */
  static runAllSync(
    registries: readonly HookRegistry[],
    type: HookType,
    context: unknown,
    ...args: readonly unknown[]
  ): void {
    for (const registry of registries) {
      for (const hook of registry.#hooks.get(type) ?? []) {
        (hook.fn as (...callArgs: unknown[]) => unknown).apply(context, args as unknown[]);
      }
    }
  }
 
  static async #runInOrder(
    hooks: readonly Hook[],
    context: unknown,
    args: readonly unknown[],
  ): Promise<void> {
    for (const hook of hooks) {
      // oxlint-disable-next-line no-await-in-loop -- hooks of one type run one after another.
      await (hook.fn as (...callArgs: unknown[]) => unknown).apply(context, args as unknown[]);
    }
  }
 
  /**
   * Returns a registry with `fn` added (to the proxied types for `beforeSave` / `afterSave`, like v6).
   *
   * @param type - Hook type.
   * @param fn - Hook function.
   * @param name - Name to remove the hook by.
   * @returns New registry; the receiver is not modified.
   * @throws Error for an unknown hook type.
   *
   * @example
   * ```ts
   * let registry!: HookRegistry;
   * const next = registry.add('beforeCreate', () => {}, 'audit');
   * next.has('beforeCreate');
   * ```
   */
  add(type: string, fn: HookFunction, name?: string): HookRegistry {
    const hook: Hook = name === undefined ? { fn } : { name, fn };
    const types = HookRegistry.#targets(type);
    return new HookRegistry(
      new Map([
        ...this.#hooks,
        ...types.map((target) => [target, [...(this.#hooks.get(target) ?? []), hook]] as const),
      ]),
    );
  }
 
  /**
   * Returns a registry without hooks matching `nameOrFn`.
   *
   * @param type - Hook type.
   * @param nameOrFn - Hook name or function; all hooks of the type when omitted.
   * @returns New registry; the receiver is not modified.
   * @throws Error for an unknown hook type.
   *
   * @example
   * ```ts
   * let registry!: HookRegistry;
   * const next = registry.remove('beforeCreate', 'audit');
   * next.has('beforeCreate');
   * ```
   */
  remove(type: string, nameOrFn?: string | HookFunction): HookRegistry {
    const types = HookRegistry.#targets(type);
    const keep = (hook: Hook): boolean =>
      nameOrFn !== undefined &&
      (typeof nameOrFn === 'string' ? hook.name !== nameOrFn : hook.fn !== nameOrFn);
    return new HookRegistry(
      new Map([
        ...this.#hooks,
        ...types.map((target) => [target, (this.#hooks.get(target) ?? []).filter(keep)] as const),
      ]),
    );
  }
 
  /**
   * Checks whether the registry has hooks of the type.
   *
   * @param type - Hook type.
   * @returns True when at least one hook exists.
   * @throws Error for an unknown hook type.
   *
   * @example
   * ```ts
   * let registry!: HookRegistry;
   * if (registry.has('afterCreate')) {
   *   console.log('afterCreate hooks registered');
   * }
   * ```
   */
  has(type: string): boolean {
    return (this.#hooks.get(HookRegistry.#assertHookType(type)) ?? []).length > 0;
  }
 
  /**
   * Like {@link HookRegistry.has}, but `undefined` for a type that never had a hook (what
   * Sequelize v6 `hasHook` returns).
   *
   * @param type - Hook type.
   * @returns Whether hooks exist, `undefined` when none was ever added.
   * @throws Error for an unknown hook type.
   * @example
   * ```ts
   * let registry!: HookRegistry;
   * const known = registry.hasOrUndefined('beforeCreate'); // undefined until a hook was added
   * ```
   */
  hasOrUndefined(type: string): boolean | undefined {
    const hooks = this.#hooks.get(HookRegistry.#assertHookType(type));
    return hooks === undefined ? undefined : hooks.length > 0;
  }
 
  /**
   * Runs the hooks of `type` in registration order.
   *
   * @param type - Hook type.
   * @param context - `this` of the hook functions.
   * @param args - Hook arguments.
   * @returns Resolves when all hooks finished; a rejecting hook stops the chain.
   *
   * @example
   * ```ts
   * let registry!: HookRegistry;
   * await registry.run('beforeCreate', User, { name: 'Ann' }, {});
   * ```
   */
  run(type: HookType, context: unknown, ...args: readonly unknown[]): Promise<void> {
    return HookRegistry.runAll([this], type, context, ...args);
  }
 
  static #targets(type: string): readonly HookType[] {
    const hookType = HookRegistry.#assertHookType(type);
    return PROXIES[hookType] ?? [hookType];
  }
 
  static #assertHookType(type: string): HookType {
    if (!HOOK_SET.has(type)) {
      throw new Error(`${type} is not a valid hook type`);
    }
    return type as HookType;
  }
}