All files / src/associations junction-keys.ts

100% Statements 23/23
90.47% Branches 19/21
100% Functions 6/6
100% Lines 23/23

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                        131x                                         131x                         110x 110x 110x       110x                           110x 110x 110x 110x   110x   110x     110x 110x       110x 110x                     220x 220x             220x               110x   110x       110x 110x      
import { inflector as inflection } from '../model/inflector.ts';
import type { ModelAttributes } from '../model/model-definition.ts';
import { ModelRegistry } from '../model/model-registry.ts';
import type { AnyModel, ModelStatic, Values } from '../model/options.ts';
import type { AssociationKeys, TargetKeys } from './association-keys.ts';
import type {
  AssociationName,
  BelongsToManyOptions,
  ForeignKeyOptions,
  ThroughOptions,
} from './types.ts';
 
const registry = new ModelRegistry();
 
type Model = ModelStatic<AnyModel>;
 
/** Alias, keys and foreign key attribute names of a belongsToMany association. */
type JunctionNames = Readonly<{
  name: AssociationName;
  sourceKey: string;
  targetKey: string;
  foreignKey: string;
  otherKey: string;
}>;
 
/** Resolves alias and keys of belongsToMany and defines the junction model's key attributes. */
export class JunctionKeys {
  readonly #keys: AssociationKeys;
 
  /**
   * @param keys - Naming and foreign key attribute rules.
   */
  constructor(keys: AssociationKeys) {
    this.#keys = keys;
  }
 
  /**
   * Resolves the alias and keys of a belongsToMany association, creating the junction model
   * when given by name and adding both foreign key attributes to it.
   *
   * @param source - Model the association is defined on.
   * @param target - Associated model.
   * @param options - Association options with `through`.
   * @returns Alias forms and keys (including the junction).
   */
  resolve(source: Model, target: Model, options: BelongsToManyOptions): TargetKeys {
    const names = this.#names(source, target, options);
    const through = this.#through(options);
    const model = this.#throughModel(source, through.model, {
      [names.foreignKey]: this.#attribute(source, names.sourceKey, options.foreignKey, options),
      [names.otherKey]: this.#attribute(target, names.targetKey, options.otherKey, options),
    } as ModelAttributes);
    return {
      name: names.name,
      keys: {
        foreignKey: names.foreignKey,
        identifierField: this.#keys.fieldOf(model, names.foreignKey),
        sourceKey: names.sourceKey,
        targetKey: names.targetKey,
        otherKey: names.otherKey,
        through: { model, ...(through.scope === undefined ? {} : { scope: through.scope }) },
      },
    };
  }
 
  #names(source: Model, target: Model, options: BelongsToManyOptions): JunctionNames {
    const keys = this.#keys;
    const name = keys.aliasNames(options.as, keys.modelName(target), true);
    const sourceKey = options.sourceKey ?? keys.primaryKey(source);
    const targetKey = options.targetKey ?? keys.primaryKey(target);
    const targetPrefix =
      source === target ? inflection.singularize(name.plural) : keys.modelName(target).singular;
    const foreignKey =
      keys.foreignKeyName(options.foreignKey) ??
      keys.camelize(`${keys.modelName(source).singular}_${sourceKey}`);
    const otherKey =
      keys.foreignKeyName(options.otherKey) ?? keys.camelize(`${targetPrefix}_${targetKey}`);
    return { name, sourceKey, targetKey, foreignKey, otherKey };
  }
 
  #through(options: BelongsToManyOptions): ThroughOptions {
    const { through } = options;
    return typeof through === 'object' && through !== null && 'model' in through
      ? through
      : { model: through };
  }
 
  #attribute(
    model: Model,
    key: string,
    option: string | ForeignKeyOptions | undefined,
    options: BelongsToManyOptions,
  ): Values {
    const keys = this.#keys;
    const spec = {
      model,
      key,
      onDelete: options.onDelete,
      onUpdate: options.onUpdate,
      constraints: options.constraints,
    };
    return keys.keyAttribute(keys.attributeOf(model, key), keys.foreignKeyExtras(option), {
      primaryKey: true,
      allowNull: false,
      ...keys.reference(spec, false, { onDelete: 'CASCADE', onUpdate: 'CASCADE' }),
    });
  }
 
  #throughModel(source: Model, through: string | Model, attributes: ModelAttributes): Model {
    const { runtime } = registry.state(source);
    const model =
      typeof through === 'string'
        ? ((runtime.models()[through] as Model | undefined) ??
          (runtime.defineModel(through, {}, { tableName: through }) as Model))
        : through;
    registry.addAssociationAttributes(model, attributes);
    return model;
  }
}