All files / src/associations nested-saver.ts

100% Statements 32/32
72.22% Branches 13/18
100% Functions 17/17
100% Lines 28/28

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              131x   131x                   131x                               3020x 15x   2x                                   1521x 15x   17x   1521x   17x           15x         2x     2x               2x 2x 2x 2x                   17x 17x 17x 2x 2x 2x   15x       15x                 2x 2x                      
import type { AnyModel, SaveOptions, Values } from '../model/options.ts';
import { ModelValues } from '../model/model-values.ts';
import type { IncludeNode } from './include.ts';
 
/** Tells model instances apart from plain values (injected to avoid importing `Model`). */
export type InstanceCheck = (value: unknown) => value is AnyModel;
 
const modelValues = new ModelValues();
 
const toArray = (value: unknown): readonly unknown[] => (Array.isArray(value) ? value : [value]);
 
/** Saves the nested instances of a nested creation, in the order Sequelize v6 does. */
export class NestedSaver {
  readonly #isInstance: InstanceCheck;
 
  /**
   * @param isInstance - Checks whether a value is a model instance.
   */
  constructor(isInstance: InstanceCheck) {
    this.#isInstance = isInstance;
  }
 
  /**
   * Saves nested belongsTo parents and sets the foreign keys on the instance.
   *
   * @param instance - Instance being created.
   * @param includes - Include tree of the instance.
   * @param options - Save options (query options are passed on).
   * @returns Resolves when the parents are saved.
   */
  async saveBelongsTo(
    instance: AnyModel,
    includes: readonly IncludeNode[],
    options: SaveOptions,
  ): Promise<void> {
    await includes
      .filter((node) => node.association.associationType === 'BelongsTo')
      .reduce<Promise<unknown>>(
        (previous, node) => previous.then(() => this.#saveParent(instance, node, options)),
        Promise.resolve(),
      );
  }
 
  /**
   * Saves nested hasOne / hasMany / belongsToMany children after the instance, one at a time.
   *
   * @param instance - Saved instance.
   * @param includes - Include tree of the instance.
   * @param options - Save options (query options are passed on).
   * @returns Resolves when the children are saved.
   */
  async saveChildren(
    instance: AnyModel,
    includes: readonly IncludeNode[],
    options: SaveOptions,
  ): Promise<void> {
    const pairs = includes
      .filter((node) => node.association.associationType !== 'BelongsTo')
      .flatMap((node) =>
        this.#nestedInstances(instance, node).map((child) => [node, child] as const),
      );
    await pairs.reduce<Promise<unknown>>(
      (previous, [node, child]) =>
        previous.then(() => this.#saveChild(instance, node, child, options)),
      Promise.resolve(),
    );
  }
 
  #nestedInstances(instance: AnyModel, node: IncludeNode): readonly AnyModel[] {
    return toArray((instance.dataValues as Values)[node.as]).filter(this.#isInstance);
  }
 
  #throughValues(child: AnyModel, node: IncludeNode): Values {
    const value =
      node.through === undefined
        ? undefined
        : (child.dataValues as Values)[node.through.definition.name];
    return this.#isInstance(value)
      ? (value.get({ plain: true }) as Values)
      : typeof value === 'object' && value !== null
        ? (value as Values)
        : {};
  }
 
  async #saveParent(instance: AnyModel, node: IncludeNode, options: SaveOptions): Promise<void> {
    const [parent] = this.#nestedInstances(instance, node);
    Eif (parent !== undefined) {
      await parent.save(modelValues.queryOptions(options));
      instance.set(node.association.foreignKey, parent.get(node.association.targetKey));
    }
  }
 
  async #saveChild(
    instance: AnyModel,
    node: IncludeNode,
    child: AnyModel,
    options: SaveOptions,
  ): Promise<void> {
    const { association } = node;
    const childOptions = modelValues.queryOptions(options);
    if (association.associationType === 'BelongsToMany' && association.through !== undefined) {
      await child.save(childOptions);
      await this.#saveJunction(instance, node, child, childOptions);
      return;
    }
    child.set({
      ...association.scope,
      [association.foreignKey]: instance.get(association.sourceKey),
    });
    await child.save(childOptions);
  }
 
  async #saveJunction(
    instance: AnyModel,
    node: IncludeNode,
    child: AnyModel,
    childOptions: ReturnType<ModelValues['queryOptions']>,
  ): Promise<void> {
    const { association } = node;
    await association.through?.model.create(
      {
        ...this.#throughValues(child, node),
        ...association.through.scope,
        [association.foreignKey]: instance.get(association.sourceKey),
        [association.otherKey ?? '']: child.get(association.targetKey),
      } as never,
      childOptions as never,
    );
  }
}