All files / src/model/operations create-operation.ts

100% Statements 24/24
75% Branches 9/12
100% Functions 3/3
100% Lines 24/24

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                                                                                                            3006x       3006x 3004x   2x 2x 2x       2x 2x 2x   2x 2x   2x 2x 1x 1x   1x 1x   1x       2x 2x 2x             2x 2x 2x                
import { InstanceState } from '../instance-state.ts';
import type { ModelDefinition } from '../model-definition.ts';
import type { ModelRegistry } from '../model-registry.ts';
import type { ModelValues } from '../model-values.ts';
import type { OnConflictBuilder, OnConflictOptions } from '../on-conflict-builder.ts';
import type {
  AnyModel,
  CreateOptions,
  ModelStatic,
  MutableOptions,
  SaveOptions,
  Values,
} from '../options.ts';
import type { InsertOperation } from './insert-operation.ts';
import { ModelOperation, type OperationServices } from './model-operation.ts';
 
/** Collaborators of {@link CreateOperation}. */
export type CreateOperationServices = OperationServices &
  Readonly<{
    /** Model state. */
    registry: ModelRegistry;
    /** Value rules. */
    values: ModelValues;
    /** ON CONFLICT builder. */
    conflicts: OnConflictBuilder;
    /** Conflict-aware inserts. */
    inserter: InsertOperation;
  }>;
 
// One `Model.create` call with `onConflict`: the built instance and both option objects.
type CreateCall = Readonly<{
  model: ModelStatic<AnyModel>;
  definition: ModelDefinition;
  instance: AnyModel;
  opts: MutableOptions;
  options: CreateOptions;
}>;
 
/** `Model.create`: builds and saves an instance, or inserts it with `onConflict`. */
export class CreateOperation extends ModelOperation<CreateOperationServices> {
  /**
   * `Model.create`.
   *
   * @param model - Model class.
   * @param values - Attribute values.
   * @param options - Create options.
   * @returns Saved instance (with `onConflict`: the written row, or the unsaved instance with
   * `wasInserted: false` when nothing was written).
   */
  async create<M extends AnyModel>(
    model: ModelStatic<M>,
    values: Values | undefined,
    options: CreateOptions,
  ): Promise<M> {
    const instance = new model(
      values,
      options.include === undefined ? {} : { include: options.include },
    );
    if (options.onConflict === undefined) {
      return instance.save(options as SaveOptions);
    }
    const { definition } = this.services.registry.state(model);
    const opts: MutableOptions = { hooks: true, validate: true, ...options };
    return (await this.#createOnConflict({ model, definition, instance, opts, options })) as M;
  }
 
  async #createOnConflict(call: CreateCall): Promise<AnyModel> {
    const { model, instance, opts } = call;
    Eif (opts['validate'] === true) {
      await instance.validate({ hooks: opts['hooks'] === true });
    }
    Eif (opts['hooks'] === true) {
      await this.services.lifecycle.runHooks(model, 'beforeCreate', instance, opts);
    }
    const [inserted] = await this.#insert(call);
    if (inserted === undefined) {
      InstanceState.of(instance).wasInserted = false;
      return instance;
    }
    Eif (opts['hooks'] === true) {
      await this.services.lifecycle.runHooks(model, 'afterCreate', inserted, opts);
    }
    return inserted;
  }
 
  #insert({ model, definition, instance, opts, options }: CreateCall): Promise<AnyModel[]> {
    const { conflicts, inserter, values } = this.services;
    const silent = opts['silent'] === true;
    const row = values.withTimestamps(
      definition,
      instance.dataValues as Values,
      new Date(),
      true,
      silent,
    );
    const fields = options.fields as readonly string[] | undefined;
    const onConflict = options.onConflict as OnConflictOptions<unknown>;
    return inserter.withConflict(
      model,
      [values.pick(row, fields)],
      conflicts.build(definition, onConflict),
      options,
    );
  }
}