All files / src/associations has-many.ts

100% Statements 38/38
78.94% Branches 15/19
100% Functions 13/13
100% Lines 36/36

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                  131x 131x                                 184x 184x 184x 184x                                       5x 1x   4x                   3x 1x       1x 1x 3x   1x 3x   1x                     2x                             2x 2x                                 1x 1x 1x         1x                               1x 1x 1x               1x                       1x 1x                   1x 1x         1x                               2x             14x       6x      
import { Op } from '../expressions/op.ts';
import type { AnyModel, CountOptions, ModelStatic, Values } from '../model/options.ts';
import { Association, type AccessorOptions } from './association.ts';
import { AssociationKeys } from './association-keys.ts';
import { OwnerKeys } from './owner-keys.ts';
import type { AssociationOptions } from './types.ts';
 
type Instance = AnyModel;
 
const keys = new AssociationKeys();
const ownerKeys = new OwnerKeys(keys);
 
/** `source.hasMany(target)` (Sequelize v6 `HasMany`): the foreign key lives on the target. */
export class HasMany<
  S extends AnyModel = AnyModel,
  T extends AnyModel = AnyModel,
> extends Association<S, T> {
  readonly #targetPk: string;
 
  /**
   * Adds the foreign key attribute to the target and registers the association.
   *
   * @param source - Model the association is defined on.
   * @param target - Associated model.
   * @param options - Association options.
   */
  constructor(source: ModelStatic<S>, target: ModelStatic<T>, options: AssociationOptions = {}) {
    const resolved = ownerKeys.hasOneOrMany(true, source, target, options);
    super('HasMany', source, target, options, resolved.name, resolved.keys);
    this.#targetPk = keys.primaryKey(target);
    this.install();
  }
 
  /**
   * Loads the associated instances (`getXs`); given an array of source instances it loads the rows of all
   * of them with one query.
   *
   * @param instance - Source instance, or an array of them.
   * @param options - Find options.
   * @returns Associated instances; for an array, an object keyed by the source key value with the instances of each source.
   */
  get(
    instances: readonly Instance[],
    options?: AccessorOptions,
  ): Promise<Record<string, Instance[]>>;
  get(instance: Instance, options?: AccessorOptions): Promise<Instance[]>;
  get(
    instance: Instance | readonly Instance[],
    options: AccessorOptions = {},
  ): Promise<Instance[] | Record<string, Instance[]>> {
    if (Array.isArray(instance)) {
      return this.#getMany(instance as readonly Instance[], options);
    }
    return this.target.findAll({
      ...options,
      where: this.andWhere(options.where, this.scope, this.#own(instance as Instance)),
    } as never);
  }
 
  async #getMany(
    instances: readonly Instance[],
    options: AccessorOptions,
  ): Promise<Record<string, Instance[]>> {
    const values = instances.map((instance) => instance.get(this.sourceKey));
    const found = await this.target.findAll({
      ...options,
      where: this.andWhere(options.where, this.scope, { [this.foreignKey]: { [Op.in]: values } }),
    } as never);
    const result: Record<string, Instance[]> = {};
    for (const key of values) {
      result[String(key)] = [];
    }
    for (const row of found as readonly Instance[]) {
      result[String(row.get(this.foreignKey))]?.push(row);
    }
    return result;
  }
 
  /**
   * Counts the associated instances (`countXs`).
   *
   * @param instance - Source instance.
   * @param options - Count options.
   * @returns Number of associated rows.
   */
  count(instance: Instance, options: AccessorOptions = {}): Promise<number> {
    return this.target.count({
      ...options,
      where: this.andWhere(options.where, this.scope, this.#own(instance)),
    } as CountOptions);
  }
 
  /**
   * Checks whether all given instances are associated (`hasX` / `hasXs`).
   *
   * @param instance - Source instance.
   * @param item - Instance(s) or primary key value(s).
   * @param options - Query options.
   * @returns True when every item is associated.
   */
  async has(instance: Instance, item: unknown, options: AccessorOptions = {}): Promise<boolean> {
    const wanted = this.#ids(item);
    return (
      (await this.target.count({
        ...this.passThrough(options),
        where: this.andWhere(this.scope, this.#own(instance), { [this.#targetPk]: wanted }),
      } as CountOptions)) === wanted.length
    );
  }
 
  /**
   * Links the given instances to the source (`addX` / `addXs`).
   *
   * @param instance - Source instance.
   * @param items - Instance(s) or primary key value(s).
   * @param options - Query options.
   * @returns The source instance.
   */
  async add(instance: Instance, items: unknown, options: AccessorOptions = {}): Promise<Instance> {
    const wanted = this.#ids(items);
    Eif (wanted.length > 0) {
      await this.target.update(
        { ...this.#own(instance), ...this.scope } as never,
        { ...this.passThrough(options), where: { [this.#targetPk]: wanted } } as never,
      );
    }
    return instance;
  }
 
  /**
   * Unlinks the given instances (`removeX` / `removeXs`).
   *
   * @param instance - Source instance.
   * @param items - Instance(s) or primary key value(s).
   * @param options - Query options.
   * @returns The source instance.
   */
  async remove(
    instance: Instance,
    items: unknown,
    options: AccessorOptions = {},
  ): Promise<Instance> {
    const wanted = this.#ids(items);
    Eif (wanted.length > 0) {
      await this.target.update(
        { [this.foreignKey]: null } as never,
        {
          ...this.passThrough(options),
          where: this.andWhere(this.#own(instance), { [this.#targetPk]: wanted }),
        } as never,
      );
    }
    return instance;
  }
 
  /**
   * Replaces the associated instances (`setXs`).
   *
   * @param instance - Source instance.
   * @param items - Instance(s) or primary key value(s).
   * @param options - Query options.
   * @returns The source instance.
   */
  async set(instance: Instance, items: unknown, options: AccessorOptions = {}): Promise<Instance> {
    const wanted = this.#ids(items);
    await this.target.update(
      { [this.foreignKey]: null } as never,
      {
        ...this.passThrough(options),
        where: this.andWhere(
          this.#own(instance),
          wanted.length === 0 ? undefined : { [this.#targetPk]: { [Op.notIn]: wanted } },
        ),
      } as never,
    );
    Eif (wanted.length > 0) {
      await this.target.update(
        { ...this.#own(instance), ...this.scope } as never,
        { ...this.passThrough(options), where: { [this.#targetPk]: wanted } } as never,
      );
    }
    return instance;
  }
 
  /**
   * Creates an associated instance linked to the source (`createX`).
   *
   * @param instance - Source instance.
   * @param values - Values of the new instance.
   * @param options - Query options.
   * @returns The created instance.
   */
  create(
    instance: Instance,
    values: Values = {},
    options: AccessorOptions = {},
  ): Promise<Instance> {
    return this.target.create(
      { ...values, ...this.scope, ...this.#own(instance) } as never,
      this.passThrough(options) as never,
    );
  }
 
  #own(instance: Instance): Values {
    return { [this.foreignKey]: instance.get(this.sourceKey) };
  }
 
  #ids(items: unknown): readonly unknown[] {
    return this.toArray(items).map((item) => this.keyOf(item, this.#targetPk));
  }
}