All files / src/associations association-shape.ts

100% Statements 3/3
100% Branches 4/4
100% Functions 1/1
100% Lines 3/3

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                                                131x                 521x 521x                                
import type { AnyModel, ModelStatic } from '../model/options.ts';
import { AssociationAccessors } from './association-accessors.ts';
import type { AssociationKeyFields } from './association-key-types.ts';
import type {
  Association as AssociationFields,
  AssociationName,
  AssociationOptions,
  AssociationType,
} from './types.ts';
 
type Model = ModelStatic<AnyModel>;
 
/** Everything an association is built from. */
export type AssociationInit = Readonly<{
  type: AssociationType;
  source: Model;
  target: Model;
  options: AssociationOptions;
  name: AssociationName;
  keys: AssociationKeyFields;
}>;
 
/** Computes the public fields of an association from its definition. */
export class AssociationShape {
  readonly #accessors = new AssociationAccessors();
 
  /**
   * Public fields of an association.
   *
   * @param init - Kind, models, options, alias forms and resolved keys.
   * @returns Field values.
   */
  fields(init: AssociationInit): AssociationFields {
    const multi = init.type === 'HasMany' || init.type === 'BelongsToMany';
    return {
      ...init.keys,
      associationType: init.type,
      source: init.source,
      target: init.target,
      as: multi ? init.name.plural : init.name.singular,
      name: init.name,
      isAliased: init.options.as !== undefined,
      scope: init.options.scope,
      isSingleAssociation: !multi,
      isMultiAssociation: multi,
      accessors: this.#accessors.namesFor(init.type, init.name),
      options: init.options,
    };
  }
}