All files / src/model definition-normalizer.ts

100% Statements 37/37
94.73% Branches 36/38
100% Functions 17/17
100% Lines 34/34

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                            132x                                                           1822x 1822x 1822x 1822x 1822x 1822x                         1822x 1822x 1822x 1822x         7630x   7630x 1940x               1822x 1822x 1822x                                 2587x       1822x       1822x             1822x           7634x               7634x 7634x                 3642x       3643x 6103x 410x   3233x 1x       3232x                     1821x   3642x 2528x                
import inflection from 'inflection';
import type { ModelDefaults } from '../connection/options.ts';
import { DataTypes } from '../data-types/data-types.ts';
import { AttributeNormalizer } from './attribute-normalizer.ts';
import type { AttributeDefinition, ModelAttributes } from './attribute-options.ts';
import type { DefinitionOptions, ModelDefinitionFields } from './model-definition.ts';
 
type SpecialAttributes = Readonly<{
  createdAt: string | undefined;
  updatedAt: string | undefined;
  deletedAt: string | undefined;
  version: string | undefined;
}>;
 
const attributes = new AttributeNormalizer();
 
/**
 * Normalizes `Model.init` arguments into the fields of a model definition, applying Sequelize v6
 * defaults (table name, automatic primary key, timestamps, paranoid, version, unique keys).
 *
 * @internal
 */
export class DefinitionNormalizer {
  readonly #attributes: ModelAttributes;
  readonly #associationAttributes: ModelAttributes;
  readonly #options: DefinitionOptions;
  readonly #name: string;
  readonly #underscored: boolean;
  readonly #tableName: string;
 
  /**
   * @param className - Class name (default model name).
   * @param declared - Declared attributes.
   * @param options - Model options.
   * @param defaults - `define` defaults of the Sequelize instance.
   * @param associationAttributes - Attributes added by associations (foreign keys).
   */
  constructor(
    className: string,
    declared: ModelAttributes,
    options: DefinitionOptions,
    defaults: ModelDefaults,
    associationAttributes: ModelAttributes,
  ) {
    this.#attributes = declared;
    this.#associationAttributes = associationAttributes;
    this.#options = { timestamps: true, ...defaults, ...options };
    this.#name = this.#options.modelName ?? className;
    this.#underscored = this.#options.underscored === true;
    this.#tableName =
      this.#options.tableName ??
      (this.#options.freezeTableName === true
        ? this.#name
        : attributes.underscoredIf(inflection.pluralize(this.#name), this.#underscored));
  }
 
  /**
   * Normalized definition fields.
   *
   * @returns The fields.
   */
  fields(): ModelDefinitionFields {
    const special = this.#specialAttributes();
    const normalized = this.#normalizedAttributes(special);
    const list = [...normalized.values()];
    return {
      name: this.#name,
      tableName: this.#tableName,
      schema: this.#options.schema,
      attributes: normalized,
      fieldToAttribute: new Map(list.map((attribute) => [attribute.field, attribute.fieldName])),
      primaryKeys: list
        .filter((attribute) => attribute.primaryKey === true)
        .map((attribute) => attribute.fieldName),
      ...special,
      uniqueKeys: attributes.uniqueKeys(this.#tableName, list),
      options: this.#options,
    };
  }
 
  #specialAttributes(): SpecialAttributes {
    const options = this.#options;
    const timestamps = options.timestamps === true;
    return {
      createdAt: timestamps ? this.#timestampName(options.createdAt, 'createdAt') : undefined,
      updatedAt: timestamps ? this.#timestampName(options.updatedAt, 'updatedAt') : undefined,
      deletedAt:
        timestamps && options.paranoid === true
          ? this.#timestampName(options.deletedAt, 'deletedAt')
          : undefined,
      version:
        options.version === undefined || options.version === false
          ? undefined
          : typeof options.version === 'string'
            ? options.version
            : 'version',
    };
  }
 
  #timestampName(option: string | boolean | undefined, fallback: string): string | undefined {
    return option === false ? undefined : typeof option === 'string' ? option : fallback;
  }
 
  #normalizedAttributes(special: SpecialAttributes): Map<string, AttributeDefinition> {
    const withAssociations: ModelAttributes = {
      ...this.#associationAttributes,
      ...this.#attributes,
    };
    const generated = new Set([
      ...Object.keys(this.#autoPrimaryKey(withAssociations)),
      special.createdAt,
      special.updatedAt,
      special.deletedAt,
      special.version,
    ]);
    const all: ModelAttributes = {
      ...this.#autoPrimaryKey(withAssociations),
      ...this.#attributes,
      ...this.#undeclared(this.#timestampAttributes(special)),
      ...this.#undeclared(this.#associationAttributes),
    };
    return new Map(Object.entries(all).map(([name, input]) => this.#entry(name, input, generated)));
  }
 
  #entry(
    name: string,
    input: ModelAttributes[string],
    generated: ReadonlySet<string | undefined>,
  ): readonly [string, AttributeDefinition] {
    const definition = attributes.attribute(name, input, this.#underscored);
    return [
      name,
      generated.has(name) && !(name in this.#attributes)
        ? Object.freeze({ ...definition, _autoGenerated: true })
        : definition,
    ];
  }
 
  #undeclared(added: ModelAttributes): ModelAttributes {
    return Object.fromEntries(Object.entries(added).filter(([key]) => !(key in this.#attributes)));
  }
 
  #autoPrimaryKey(declared: ModelAttributes): ModelAttributes {
    const entries = Object.values(declared);
    if (entries.some((value) => attributes.isOptions(value) && value.primaryKey === true)) {
      return {};
    }
    if ('id' in declared) {
      throw new Error(
        `A column called 'id' was added to the attributes of '${this.#tableName}' but not marked with 'primaryKey: true'`,
      );
    }
    return {
      id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    };
  }
 
  #timestampAttributes({
    createdAt,
    updatedAt,
    deletedAt,
    version,
  }: SpecialAttributes): ModelAttributes {
    return Object.fromEntries([
      ...[createdAt, updatedAt]
        .filter((name): name is string => name !== undefined)
        .map((name) => [name, { type: DataTypes.DATE, allowNull: false }] as const),
      ...(deletedAt === undefined ? [] : [[deletedAt, { type: DataTypes.DATE }] as const]),
      ...(version === undefined
        ? []
        : [[version, { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }] as const]),
    ]);
  }
}