All files / src/associations association-keys.ts

95.23% Statements 20/21
74.41% Branches 32/43
100% Functions 13/13
95.23% Lines 20/21

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              131x                                       408x   408x                   833x 833x 833x                         1060x                     1152x                     521x                   631x                   631x                               521x                                   631x     631x 631x                                                       631x                                                 411x 411x 411x                   411x              
import { inflector as inflection } from '../model/inflector.ts';
import type { AttributeDefinition, ModelAttributes } from '../model/model-definition.ts';
import type { AnyModel, ModelStatic, Values } from '../model/options.ts';
import { ModelRegistry } from '../model/model-registry.ts';
import type { ReferenceDefaults, ReferenceSpec } from './association-key-types.ts';
import type { AssociationName, AssociationOptions, ForeignKeyOptions } from './types.ts';
 
const registry = new ModelRegistry();
 
type Model = ModelStatic<AnyModel>;
 
export type {
  AssociationKeyFields,
  ReferenceDefaults,
  ReferenceSpec,
  TargetKeys,
} from './association-key-types.ts';
 
/** Naming and foreign key attribute rules shared by the association classes (Sequelize v6 defaults). */
export class AssociationKeys {
  /**
   * Converts `snake_case` / `kebab-case` / spaced names to camelCase.
   *
   * @param value - Name to convert.
   * @returns camelCase name.
   */
  camelize(value: string): string {
    return value
      .trim()
      .replace(/[-_\s]+(.)?/g, (_match, char?: string) => (char ?? '').toUpperCase());
  }
 
  /**
   * Singular and plural forms of a model name.
   *
   * @param model - Model class.
   * @returns Name forms.
   */
  modelName(model: Model): AssociationName {
    const definition = registry.state(model).definition;
    const forms = definition.options.name;
    return {
      singular: forms?.singular ?? inflection.singularize(definition.name),
      plural: forms?.plural ?? inflection.pluralize(definition.name),
    };
  }
 
  /**
   * First primary key attribute of a model.
   *
   * @param model - Model class.
   * @returns Attribute name (`id` when the model has none).
   */
  primaryKey(model: Model): string {
    return registry.state(model).definition.primaryKeys[0] ?? 'id';
  }
 
  /**
   * Attribute definition by name.
   *
   * @param model - Model class.
   * @param name - Attribute name.
   * @returns Definition, if the attribute exists.
   */
  attributeOf(model: Model, name: string): AttributeDefinition | undefined {
    return registry.state(model).definition.attributes.get(name);
  }
 
  /**
   * Column of an attribute.
   *
   * @param model - Model class.
   * @param name - Attribute name.
   * @returns Column name (the attribute name when not defined).
   */
  fieldOf(model: Model, name: string): string {
    return this.attributeOf(model, name)?.field ?? name;
  }
 
  /**
   * Attribute name of a `foreignKey` / `otherKey` option.
   *
   * @param option - Option value.
   * @returns Attribute name, if given.
   */
  foreignKeyName(option: string | ForeignKeyOptions | undefined): string | undefined {
    return option === undefined ? undefined : typeof option === 'string' ? option : option.name;
  }
 
  /**
   * Object form of a `foreignKey` / `otherKey` option.
   *
   * @param option - Option value.
   * @returns Foreign key options (empty for a string).
   */
  foreignKeyExtras(option: string | ForeignKeyOptions | undefined): ForeignKeyOptions {
    return option === undefined || typeof option === 'string' ? {} : option;
  }
 
  /**
   * Singular and plural alias forms.
   *
   * @param as - `as` option.
   * @param fallback - Forms used without `as`.
   * @param multi - Whether a string alias is the plural form.
   * @returns Alias forms.
   */
  aliasNames(
    as: string | AssociationName | undefined,
    fallback: AssociationName,
    multi: boolean,
  ): AssociationName {
    return as === undefined
      ? fallback
      : typeof as === 'string'
        ? multi
          ? { singular: inflection.singularize(as), plural: as }
          : { singular: as, plural: inflection.pluralize(as) }
        : as;
  }
 
  /**
   * `references` / `onDelete` / `onUpdate` attribute options of a foreign key.
   *
   * @param spec - Referenced model and key, with the actions from the options.
   * @param allowNull - Whether the key may be `NULL` (for the `auto` delete action).
   * @param defaults - Actions used when the options give none.
   * @returns Attribute options (empty with `constraints: false`).
   */
  reference(spec: ReferenceSpec, allowNull: boolean, defaults: ReferenceDefaults): Values {
    Iif (spec.constraints === false) {
      return {};
    }
    const definition = registry.state(spec.model).definition;
    return {
      references: {
        model: {
          tableName: definition.tableName,
          ...(definition.schema === undefined ? {} : { schema: definition.schema }),
        },
        key: definition.attributes.get(spec.key)?.field ?? spec.key,
      },
      onDelete:
        spec.onDelete ??
        (defaults.onDelete === 'auto' ? (allowNull ? 'SET NULL' : 'NO ACTION') : defaults.onDelete),
      onUpdate: spec.onUpdate ?? defaults.onUpdate,
    };
  }
 
  /**
   * Attribute options of a foreign key.
   *
   * @param type - Referenced attribute (its data type is reused).
   * @param extras - Object form of the foreign key option.
   * @param base - Further attribute options.
   * @returns Attribute options.
   */
  keyAttribute(
    type: AttributeDefinition | undefined,
    extras: ForeignKeyOptions,
    base: Values = {},
  ): Values {
    return {
      type: type?.type,
      allowNull: true,
      ...base,
      ...(extras.field === undefined ? {} : { field: extras.field }),
      ...(extras.allowNull === undefined ? {} : { allowNull: extras.allowNull }),
    };
  }
 
  /**
   * Adds the foreign key attribute (with its reference) to the model that holds the key.
   *
   * @param owner - Model that holds the foreign key.
   * @param referenced - Model the key references.
   * @param referencedKey - Referenced attribute.
   * @param foreignKey - Foreign key attribute name.
   * @param options - Association options.
   */
  addForeignKey(
    owner: Model,
    referenced: Model,
    referencedKey: string,
    foreignKey: string,
    options: AssociationOptions,
  ): void {
    const extras = this.foreignKeyExtras(options.foreignKey);
    const spec = { model: referenced, key: referencedKey, ...this.#actions(options) };
    registry.addAssociationAttributes(owner, {
      [foreignKey]: this.keyAttribute(
        this.attributeOf(referenced, referencedKey),
        extras,
        this.reference(spec, extras.allowNull !== false, { onDelete: 'auto', onUpdate: 'CASCADE' }),
      ),
    } as ModelAttributes);
  }
 
  #actions(options: AssociationOptions): Omit<ReferenceSpec, 'model' | 'key'> {
    return {
      onDelete: options.onDelete,
      onUpdate: options.onUpdate,
      constraints: options.constraints,
    };
  }
}