All files / src/model instance-saver.ts

100% Statements 48/48
96.77% Branches 30/31
100% Functions 14/14
100% Lines 46/46

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                                              131x 131x 131x                     3099x   3099x   3099x 3099x 3099x   3088x 3x   3085x     1584x 1566x     1583x         1583x 1566x   17x 34x           3099x 3031x 3031x 3031x               3099x 3099x 3099x                                 3065x         3235x 3842x 3842x                   4636x 4636x               3099x 3099x 3092x   3088x 18x   3070x 3070x 3070x 3030x   40x                   40x 40x 40x   235x     40x      
import type { HookType } from '../hooks/hooks.ts';
import type { InstanceLifecycleServices } from './instance-lifecycle-services.ts';
import type { InstanceLifecycle } from './instance-lifecycle.ts';
import { InstanceState } from './instance-state.ts';
import { InstanceWriter, type SaveContext } from './instance-writer.ts';
import type { AnyModel, SaveOptions, Values } from './options.ts';
 
/**
 * `instance.save()`: validation, `beforeCreate` / `beforeUpdate` hooks (with re-validation of
 * attributes the hooks changed), the INSERT or UPDATE, then the `after` hooks.
 *
 * @internal
 */
export class InstanceSaver {
  readonly #services: InstanceLifecycleServices;
  readonly #lifecycle: InstanceLifecycle;
  readonly #writer: InstanceWriter;
 
  /**
   * @param services - Collaborators.
   * @param lifecycle - Hook runner and row refresh.
   */
  constructor(services: InstanceLifecycleServices, lifecycle: InstanceLifecycle) {
    this.#services = services;
    this.#lifecycle = lifecycle;
    this.#writer = new InstanceWriter(services, lifecycle);
  }
 
  /**
   * 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.
   */
  async save<I extends AnyModel>(instance: I, options: SaveOptions): Promise<I> {
    const context = this.#context(instance, options);
    const fields =
      context.explicitFields ??
      (context.isNew ? this.#attributes(context) : this.#changed(context));
    const now = new Date();
    this.#stampNew(instance, context, now);
    const hookFields = await this.#prepare(instance, context, fields);
    // like v6, validation and the before hooks run even when nothing changed; they may still change something
    if (!context.isNew && this.#changed(context).length === 0 && hookFields.length === 0) {
      return instance;
    }
    await (context.isNew
      ? this.#writer.insert(instance, context, now)
      : this.#writer.update(instance, context, hookFields, now));
    if (context.opts['hooks'] === true) {
      await this.#hook(instance, context, 'afterCreate', 'afterUpdate');
    }
    // v6 resets previous values and `changed` only after the after hooks, which still read them
    return this.#lifecycle.settle(instance, this.#settled(context, hookFields));
  }
 
  // With a `fields` option only those attributes (and the timestamps the save wrote) become unchanged.
  #settled(context: SaveContext, written: readonly string[]): readonly string[] | undefined {
    if (context.explicitFields === undefined) {
      return undefined;
    }
    const { createdAt, updatedAt } = context.definition;
    return [...written, ...[createdAt, updatedAt].filter((name) => name !== undefined)];
  }
 
  // Like v6, a new record gets its `createdAt` / `updatedAt` before validation, so a timestamp attribute
  // declared with `allowNull: false` passes the not-null check.
  #stampNew(instance: AnyModel, context: SaveContext, now: Date): void {
    if (context.isNew) {
      const silent = context.opts['silent'] === true;
      const values = instance.dataValues as Values;
      Object.assign(
        values,
        this.#services.values.withTimestamps(context.definition, values, now, true, silent),
      );
    }
  }
 
  #context(instance: AnyModel, options: SaveOptions): SaveContext {
    const model = instance.constructor;
    const { definition, runtime } = this.#services.registry.state(model);
    return {
      model,
      definition,
      runtime,
      state: InstanceState.of(instance),
      opts: { hooks: true, validate: true, ...options },
      options,
      isNew: instance.isNewRecord,
      explicitFields: this.#services.values.saveFields(
        definition,
        options.fields as readonly string[] | undefined,
        instance.isNewRecord,
      ),
    };
  }
 
  #attributes(context: SaveContext): readonly string[] {
    return [...context.definition.attributes.keys()];
  }
 
  #changed({ state, definition }: SaveContext): readonly string[] {
    // virtual attributes have no column to write
    return [...state.changed].filter((name) => {
      const attribute = definition.attributes.get(name);
      return attribute !== undefined && attribute.type.isVirtual !== true;
    });
  }
 
  #hook(
    instance: AnyModel,
    context: SaveContext,
    create: HookType,
    update: HookType,
  ): Promise<void> {
    const type = context.isNew ? create : update;
    return this.#lifecycle.runHooks(context.model, type, instance, context.opts);
  }
 
  async #prepare(
    instance: AnyModel,
    context: SaveContext,
    fields: readonly string[],
  ): Promise<readonly string[]> {
    const { opts } = context;
    if (opts['validate'] === true) {
      await instance.validate({ hooks: opts['hooks'] === true, fields });
    }
    if (opts['hooks'] !== true) {
      return fields;
    }
    const before = this.#changed(context);
    await this.#hook(instance, context, 'beforeCreate', 'beforeUpdate');
    if (context.explicitFields !== undefined || context.isNew) {
      return fields;
    }
    return this.#addChanged(instance, context, fields, before);
  }
 
  /** Adds attributes changed by `beforeUpdate` hooks to the saved fields, validating them. */
  async #addChanged(
    instance: AnyModel,
    context: SaveContext,
    fields: readonly string[],
    before: readonly string[],
  ): Promise<readonly string[]> {
    const added = this.#changed(context).filter((name) => !before.includes(name));
    Eif (context.opts['validate'] === true) {
      await instance.validate({
        hooks: context.opts['hooks'] === true,
        skip: this.#attributes(context).filter((name) => !added.includes(name)),
      });
    }
    return [...fields, ...added];
  }
}