All files / src/model instance-lifecycle.ts

98.9% Statements 90/91
97.43% Branches 38/39
96.77% Functions 30/31
98.86% Lines 87/88

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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363                                                                                    131x 131x 131x 131x                       35653x 35653x 35653x           35653x           35367x 35367x 61x                                         1914x                       139583x 139583x 139583x 139583x 139583x 139583x 139583x   344095x     139583x 139583x 3772x 3772x                         3435x                       2x                     3099x                         25x 25x 25x 25x 25x 3x       22x 22x 22x 22x 22x 22x         25x 25x       3x             22x 22x 21x 121x     22x 126x 1x 22x                     26x                             5x                     3x                                   2x 2x 2x 2x                                     102284x                                 103805x 103803x     103805x 103805x                     103867x 103867x 103850x 103850x 103850x   17x 17x 17x 17x 80x 80x   17x                 139583x 139573x 139573x   10x 15x 23x 10x 139583x 139583x       10x 15x 15x 13x          
import type { IncludeNode } from '../associations/include.ts';
import { InstanceError } from '../errors/errors.ts';
import { HookRegistry, type HookType } from '../hooks/hooks.ts';
import { transactionScope } from '../transaction/transaction-runner.ts';
import { InstanceDestroyer } from './instance-destroyer.ts';
import type { InstanceLifecycleServices, ValidateOptions } from './instance-lifecycle-services.ts';
import { InstanceSaver } from './instance-saver.ts';
import { InstanceState } from './instance-state.ts';
import { InstanceValidation } from './instance-validation.ts';
import type { ModelDefinition } from './model-definition.ts';
import type {
  AnyModel,
  AttributeAmounts,
  BuildOptions,
  FindOptions,
  IncrementOptions,
  InstanceDestroyOptions,
  ModelStatic,
  SaveOptions,
  Values,
} from './options.ts';
import type { QueryOptionsBase } from './runtime.ts';
import type { WhereOptions } from './types.ts';
 
export type { InstanceLifecycleServices, ValidateOptions } from './instance-lifecycle-services.ts';
 
/**
 * Lifecycle of model instances: construction from values (with nested includes), validation with
 * hooks, `save` (INSERT or UPDATE of changed attributes with optimistic locking), `reload`,
 * `destroy` / `restore` (soft delete for paranoid models), instance `increment` / `decrement`,
 * and the model hook runner used by every operation.
 */
export class InstanceLifecycle {
  readonly #services: InstanceLifecycleServices;
  readonly #validation: InstanceValidation;
  readonly #saver: InstanceSaver;
  readonly #destroyer: InstanceDestroyer;
 
  /**
   * @param services - Collaborators.
   */
  constructor(services: InstanceLifecycleServices) {
    this.#services = services;
    this.#validation = new InstanceValidation(services, this);
    this.#saver = new InstanceSaver(services, this);
    this.#destroyer = new InstanceDestroyer(services, this);
  }
 
  /**
   * Runs model hooks, then Sequelize-level hooks, with the model class as `this`.
   *
   * @param model - Model class.
   * @param type - Hook type.
   * @param args - Hook arguments.
   * @returns Resolves when all hooks finished.
   */
  runHooks(model: object, type: HookType, ...args: readonly unknown[]): Promise<void> {
    const { hooks, runtime } = this.#services.registry.state(model);
    InstanceLifecycle.#withActiveTransaction(args.at(-1));
    return HookRegistry.runAll([hooks, runtime.hooks()], type, model, ...args);
  }
 
  // With CLS, hooks see the current transaction in the options they receive, as in v6 (where every
  // operation puts it into its options first); queries of the operation already use it.
  static #withActiveTransaction(options: unknown): void {
    if (
      typeof options === 'object' &&
      options !== null &&
      Object.getPrototypeOf(options) === Object.prototype &&
      (options as { transaction?: unknown }).transaction === undefined
    ) {
      const active = transactionScope.active();
      if (active !== undefined) {
        (options as { transaction?: unknown }).transaction = active;
      }
    }
  }
 
  /**
   * Runs a hook for each instance, all at once like v6 (individual hooks of bulk operations).
   *
   * @param model - Model class.
   * @param type - Hook type.
   * @param instances - Instances, passed as the first hook argument.
   * @param args - Further hook arguments.
   * @returns Resolves when all hooks finished.
   */
  async runEach(
    model: object,
    type: HookType,
    instances: readonly object[],
    ...args: readonly unknown[]
  ): Promise<void> {
    // like v6 (`Promise.all`): the hook runs for every row at once, the first rejection ends the call
    await Promise.all(instances.map((instance) => this.runHooks(model, type, instance, ...args)));
  }
 
  /**
   * Initializes a new instance (`new Model(values, options)`): defaults for new records, values
   * (raw or through setters), nested include instances and change tracking.
   *
   * @param instance - Instance being constructed.
   * @param values - Attribute values (and nested include values).
   * @param options - Build options.
   */
  initialize(instance: AnyModel, values: Values, options: BuildOptions): void {
    const model = instance.constructor as ModelStatic<AnyModel>;
    const { definition } = this.#services.registry.state(model);
    const state = InstanceState.of(instance);
    instance.isNewRecord = options.isNewRecord ?? true;
    instance.dataValues = instance.isNewRecord ? this.#services.values.initial(definition) : {};
    instance._previousDataValues = {};
    const defined = Object.fromEntries(
      Object.entries(values).filter(
        ([key, value]) => value !== undefined || !(key in instance.dataValues),
      ),
    );
    state.includes = this.#assign(instance, model, defined, options);
    if (!instance.isNewRecord || options.raw === true) {
      instance._previousDataValues = { ...instance.dataValues };
      state.reset();
    }
  }
 
  /**
   * Validates an instance like Sequelize v6 `instance.validate()`.
   *
   * @param instance - Instance.
   * @param options - `hooks`, `skip`, `fields`.
   * @returns Resolves when valid.
   * @throws ValidationError with all failures.
   */
  validate(instance: AnyModel, options: ValidateOptions = {}): Promise<AnyModel> {
    return this.#validation.validate(instance, options);
  }
 
  /**
   * Validates instances of a bulk write; failures are collected into one error.
   *
   * @param instances - Instances.
   * @param hooks - Run validation hooks.
   * @returns Resolves when all are valid.
   * @throws AggregateError of BulkRecordError.
   */
  validateAll(instances: readonly AnyModel[], hooks: boolean): Promise<void> {
    return this.#validation.validateAll(instances, hooks);
  }
 
  /**
   * Inserts the instance if new, otherwise updates its changed attributes.
   *
   * @param instance - Instance.
   * @param options - Save options.
   * @returns The instance with values returned by the database.
   */
  save<I extends AnyModel>(instance: I, options: SaveOptions): Promise<I> {
    return this.#saver.save(instance, options);
  }
 
  /**
   * Reloads values from the database through `findOne`, so scopes, `paranoid`, `include`, `lock`,
   * `attributes` and find hooks apply as in Sequelize v6.
   *
   * @param instance - Instance.
   * @param options - Find options; `where` is always the primary key of the instance.
   * @returns The instance.
   * @throws InstanceError when the row no longer exists.
   */
  async reload<I extends AnyModel>(instance: I, options: FindOptions): Promise<I> {
    const model = instance.constructor as ModelStatic<AnyModel>;
    const { definition } = this.#services.registry.state(model);
    const where = this.#services.columns.primaryKeyWhere(definition, instance.dataValues as Values);
    const reloaded = await model.findOne({ ...this.#withLoadedIncludes(instance, options), where });
    if (reloaded === null) {
      throw new InstanceError(
        'Instance could not be reloaded because it does not exist anymore (find call returned null)',
      );
    }
    InstanceLifecycle.#replaceValues(instance, reloaded.dataValues as Values, options);
    instance.isNewRecord = false;
    instance._previousDataValues = { ...instance.dataValues };
    InstanceState.of(instance).reset();
    InstanceState.of(instance).loadedIncludes = InstanceState.of(reloaded).loadedIncludes;
    return instance;
  }
 
  // v6 `reload` defaults `include` to the include the instance was loaded with.
  #withLoadedIncludes(instance: AnyModel, options: FindOptions): FindOptions {
    const { loadedIncludes } = InstanceState.of(instance);
    return options.include !== undefined || loadedIncludes.length === 0
      ? options
      : {
          ...options,
          include: loadedIncludes.map((node) => this.#services.includes.toOptions(node)),
        };
  }
 
  // v6 `reload` sets the fresh values with `reset` unless `attributes` limits them; an association instance the
  // caller assigned is an own property that would hide the reloaded one, so it is dropped (v6 `_setInclude`).
  static #replaceValues(instance: AnyModel, fresh: Values, options: FindOptions): void {
    const values = instance.dataValues as Values;
    if (options.attributes === undefined) {
      Object.keys(values)
        .filter((name) => !(name in fresh))
        .forEach((name) => Reflect.deleteProperty(values, name));
    }
    Object.keys(fresh)
      .filter((name) => Object.prototype.hasOwnProperty.call(instance, name))
      .forEach((name) => Reflect.deleteProperty(instance, name));
    instance.set(fresh, { raw: true });
  }
 
  /**
   * Deletes the row of an instance (sets `deletedAt` for paranoid models unless `force`).
   *
   * @param instance - Instance.
   * @param options - Destroy options.
   * @returns The instance after a soft delete, nothing after a DELETE.
   */
  destroy(instance: AnyModel, options: InstanceDestroyOptions): Promise<AnyModel | undefined> {
    return this.#destroyer.destroy(instance, options);
  }
 
  /**
   * Restores a soft-deleted instance of a paranoid model.
   *
   * @param instance - Instance.
   * @param options - Query options; `hooks: false` skips restore hooks.
   * @returns The restored instance.
   * @throws Error when the model is not paranoid.
   */
  restore(
    instance: AnyModel,
    options: QueryOptionsBase & Readonly<{ hooks?: boolean }>,
  ): Promise<AnyModel> {
    return this.#destroyer.restore(instance, options);
  }
 
  /**
   * Whether an instance of a paranoid model is soft-deleted.
   *
   * @param instance - Instance.
   * @returns True when `deletedAt` is set.
   * @throws Error when the model is not paranoid.
   */
  isSoftDeleted(instance: AnyModel): boolean {
    return this.#destroyer.isSoftDeleted(instance);
  }
 
  /**
   * Increments / decrements attributes of the instance's row through the model static.
   *
   * @param instance - Instance.
   * @param method - `'increment'` or `'decrement'`.
   * @param fields - Attribute name(s) or map of amounts.
   * @param options - Options.
   * @returns Result of the model static.
   */
  changeBy(
    instance: AnyModel,
    method: 'increment' | 'decrement',
    fields: AttributeAmounts<Values>,
    options: Omit<IncrementOptions, 'where'>,
  ): Promise<unknown> {
    const model = instance.constructor as ModelStatic<AnyModel>;
    const { definition } = this.#services.registry.state(model);
    const where = this.#services.columns.primaryKeyWhere(definition, instance.dataValues as Values);
    return model[method](fields, {
      ...(options as IncrementOptions),
      where: where as WhereOptions,
    });
  }
 
  /**
   * Applies a returned row to an instance and marks it as persisted and unchanged.
   *
   * @param instance - Instance.
   * @param definition - Model definition.
   * @param row - Returned row (`undefined` keeps the values).
   * @returns The instance.
   */
  refresh<I extends AnyModel>(
    instance: I,
    definition: ModelDefinition,
    row: Readonly<Record<string, unknown>> | undefined,
  ): I {
    return this.settle(this.applyRow(instance, definition, row));
  }
 
  /**
   * Applies a returned row to the values of an instance, leaving its change tracking as it is, so
   * the `after` hooks of a save still see `changed()` and `previous()` (v6 `save`).
   *
   * @param instance - Instance.
   * @param definition - Model definition.
   * @param row - Returned row (`undefined` keeps the values).
   * @returns The instance.
   */
  applyRow<I extends AnyModel>(
    instance: I,
    definition: ModelDefinition,
    row: Readonly<Record<string, unknown>> | undefined,
  ): I {
    if (row !== undefined) {
      instance.set(this.#services.rows.parse(definition, row), { raw: true });
    }
    // like v6, `isNewRecord` is already false inside the after hooks
    instance.isNewRecord = false;
    return instance;
  }
 
  /**
   * Marks an instance as persisted and unchanged: previous values take the current ones.
   *
   * @param instance - Instance.
   * @param fields - Only these attributes become unchanged (the `fields` option of a save); all when omitted.
   * @returns The instance.
   */
  settle<I extends AnyModel>(instance: I, fields?: readonly string[]): I {
    instance.isNewRecord = false;
    if (fields === undefined) {
      instance._previousDataValues = { ...instance.dataValues };
      InstanceState.of(instance).reset();
      return instance;
    }
    const previous = instance._previousDataValues as Values;
    const current = instance.dataValues as Values;
    const state = InstanceState.of(instance);
    fields.forEach((name) => {
      previous[name] = current[name];
      state.mark(name, false);
    });
    return instance;
  }
 
  #assign(
    instance: AnyModel,
    model: ModelStatic<AnyModel>,
    values: Values,
    options: BuildOptions,
  ): readonly IncludeNode[] {
    if (options.include === undefined) {
      instance.set(values, options.raw === true ? { raw: true } : {});
      return [];
    }
    const includes = this.#services.includes.normalize(model, options.include);
    const nested = new Set(includes.map((node) => node.as));
    const own = Object.fromEntries(Object.entries(values).filter(([key]) => !nested.has(key)));
    instance.set(own, options.raw === true ? { raw: true } : {});
    this.#buildNested(instance, includes, values);
    return includes;
  }
 
  #buildNested(instance: AnyModel, includes: readonly IncludeNode[], values: Values): void {
    includes.forEach((node) => {
      const value = values[node.as];
      if (value !== undefined) {
        (instance.dataValues as Values)[node.as] = this.#services.nested.build(node, value);
      }
    });
  }
}