All files / src/model/operations model-operation.ts

100% Statements 9/9
50% Branches 1/2
100% Functions 5/5
100% Lines 9/9

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                                                      1179x                                   393x 393x 1093x 2180x     1093x 1093x 1087x 1087x        
import type { HookType } from '../../hooks/hooks.ts';
import type { InstanceLifecycle } from '../instance-lifecycle.ts';
import type { MutableOptions } from '../options.ts';
 
/** Services every operation has: the hook runner. */
export type OperationServices = Readonly<{
  /** Hooks. */
  lifecycle: InstanceLifecycle;
}>;
 
// oxlint-disable-next-line typescript/no-explicit-any -- decorated methods take further arguments of any type.
type OperationMethod = (model: any, options: MutableOptions, ...rest: any[]) => Promise<unknown>;
 
/**
 * Base of `Model` operations: holds the injected services and provides the hook decorators.
 *
 * @typeParam S - Services of the operation.
 * @internal
 */
export abstract class ModelOperation<S extends OperationServices> {
  /** Injected collaborators. */
  protected readonly services: S;
 
  /**
   * @param services - Collaborators.
   */
  constructor(services: S) {
    this.services = services;
  }
 
  /**
   * Method decorator: runs `before` / `after` hooks with the options around a
   * `(model, options, ...rest)` method when `options.hooks === true`.
   *
   * @param before - Hook run before the method.
   * @param after - Hook run after the method resolved.
   * @returns The decorator.
   */
  static bulkHooks(
    before: HookType,
    after: HookType,
  ): <T extends OperationMethod>(
    method: T,
    context: ClassMethodDecoratorContext<ModelOperation<OperationServices>>,
  ) => T {
    return <T extends OperationMethod>(method: T): T =>
      async function (this: ModelOperation<OperationServices>, model, options, ...rest) {
        const run = (type: HookType): Promise<void> =>
          options['hooks'] === true
            ? this.services.lifecycle.runHooks(model, type, options)
            : Promise.resolve();
        await run(before);
        const result: unknown = await method.call(this, model, options, ...rest);
        await run(after);
        return result;
      } as T;
  }
}