All files / src/model/mixins model-associations.ts

100% Statements 13/13
83.33% Branches 5/6
100% Functions 11/11
100% Lines 13/13

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                                131x 131x     42x                               5x 5x                                     4x 4x         4x                           2x                                           178x                                         49x                                         184x                                       110x        
import { BelongsTo } from '../../associations/belongs-to.ts';
import { BelongsToMany } from '../../associations/belongs-to-many.ts';
import { HasMany } from '../../associations/has-many.ts';
import { HasOne } from '../../associations/has-one.ts';
import type { Association } from '../../associations/association.ts';
import type { AssociationOptions, BelongsToManyOptions } from '../../associations/types.ts';
import { registry } from '../model-services.ts';
import type { AnyModel, ModelStatic } from '../options.ts';
import type { ModelConstructor } from './model-constructor.ts';
 
/**
 * Association statics of `Model`: `associations`, `belongsTo`, `hasOne`, `hasMany`, `belongsToMany`.
 *
 * @internal
 */
// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.
export const ModelAssociations = <TBase extends ModelConstructor>(Base: TBase) => {
  return class AssociationsCapability extends Base {
    /** Associations of the model by alias (Sequelize v6 `Model.associations`). */
    static get associations(): Readonly<Record<string, Association>> {
      return Object.fromEntries(
        registry.state(this).associations as ReadonlyMap<string, Association>,
      );
    }
 
    /**
     * Associations of this model whose target is the given model.
     *
     * @param target - Target model.
     * @returns Matching associations.
     * @example
     * ```ts
     * const toPosts = User.getAssociations(Post);
     * ```
     */
    static getAssociations(target: { name: string }): Association[] {
      return Object.values(this.associations).filter(
        (association) => (association.target as { name: string }).name === target.name,
      );
    }
 
    /**
     * Association to `target` for an alias, or the one declared without alias when `alias` is not a string.
     *
     * @param target - Target model.
     * @param alias - Association alias.
     * @returns The association, or `null`.
     * @example
     * ```ts
     * const association = User.getAssociationForAlias(Post, 'posts');
     * ```
     */
    static getAssociationForAlias(
      target: { name: string },
      alias?: string | null | { plural?: string },
    ): Association | null {
      const verifies = (association: Association): boolean =>
        typeof alias === 'string'
          ? association.as === alias
          : alias?.plural === undefined
            ? !association.isAliased
            : association.as === alias.plural;
      return this.getAssociations(target).find(verifies) ?? null;
    }
 
    /**
     * Tells whether an association with this alias exists.
     *
     * @param alias - Association alias.
     * @returns True when the model has the association.
     * @example
     * ```ts
     * if (User.hasAlias('posts')) {}
     * ```
     */
    static hasAlias(alias: string): boolean {
      return Object.hasOwn(this.associations, alias);
    }
 
    /**
     * Declares that each row of this model refers to one row of the target; the foreign key column
     * lives on this model's table. Adds accessors such as `getX` / `setX` / `createX` to instances.
     *
     * @param this - The source model class.
     * @param target - Associated model.
     * @param options - Association options.
     * @returns The association.
     * @example
     * ```ts
     * Post.belongsTo(User, { foreignKey: 'authorId', as: 'author' });
     * ```
     * @see [Associations guide](/guide/associations)
     */
    static belongsTo<M extends AnyModel, T extends AnyModel>(
      this: ModelStatic<M>,
      target: ModelStatic<T>,
      options?: AssociationOptions,
    ): BelongsTo<M, T> {
      return new BelongsTo(this, target, options);
    }
 
    /**
     * Declares that each row of this model has at most one related target row; the foreign key column
     * lives on the target's table.
     *
     * @param this - The source model class.
     * @param target - Associated model.
     * @param options - Association options.
     * @returns The association.
     * @example
     * ```ts
     * User.hasOne(Profile, { foreignKey: 'userId' });
     * ```
     */
    static hasOne<M extends AnyModel, T extends AnyModel>(
      this: ModelStatic<M>,
      target: ModelStatic<T>,
      options?: AssociationOptions,
    ): HasOne<M, T> {
      return new HasOne(this, target, options);
    }
 
    /**
     * Declares that each row of this model has many related target rows; the foreign key column
     * lives on the target's table.
     *
     * @param this - The source model class.
     * @param target - Associated model.
     * @param options - Association options.
     * @returns The association.
     * @example
     * ```ts
     * User.hasMany(Post, { foreignKey: 'authorId', as: 'posts' });
     * ```
     */
    static hasMany<M extends AnyModel, T extends AnyModel>(
      this: ModelStatic<M>,
      target: ModelStatic<T>,
      options?: AssociationOptions,
    ): HasMany<M, T> {
      return new HasMany(this, target, options);
    }
 
    /**
     * Declares a many-to-many relation between this model and the target through a junction table.
     *
     * @param this - The source model class.
     * @param target - Associated model.
     * @param options - Association options with `through`.
     * @returns The association.
     * @example
     * ```ts
     * Project.belongsToMany(Task, { through: 'ProjectTasks' });
     * ```
     */
    static belongsToMany<M extends AnyModel, T extends AnyModel>(
      this: ModelStatic<M>,
      target: ModelStatic<T>,
      options: BelongsToManyOptions,
    ): BelongsToMany<M, T> {
      return new BelongsToMany(this, target, options);
    }
  };
};