All files / src/model instance-validation.ts

100% Statements 32/32
87.5% Branches 14/16
100% Functions 11/11
100% Lines 31/31

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                                              131x 131x                       3435x 3435x 3435x 3435x 3435x 3417x   3435x 3413x 3397x   3413x               3435x 3435x 3435x 3413x   22x 22x 20x   22x                       2x   3x 1x   2x             3x 2x 2x         3435x 3435x       17342x                 3435x                            
import { AggregateError, BulkRecordError, ValidationError } from '../errors/errors.ts';
import type { ValidationErrorItem } from '../errors/errors.ts';
import type { InstanceLifecycleServices, ValidateOptions } from './instance-lifecycle-services.ts';
import type { InstanceLifecycle } from './instance-lifecycle.ts';
import type { ModelDefinition } from './model-definition.ts';
import type { ModelState } from './model-registry.ts';
import type { AnyModel } from './options.ts';
 
/**
 * Instance validation with `beforeValidate` / `afterValidate` / `validationFailed` hooks, and the
 * validation of bulk writes.
 *
 * @internal
 */
export class InstanceValidation {
  readonly #services: InstanceLifecycleServices;
  readonly #lifecycle: InstanceLifecycle;
 
  /**
   * @param services - Collaborators.
   * @param lifecycle - Hook runner.
   */
  constructor(services: InstanceLifecycleServices, lifecycle: InstanceLifecycle) {
    this.#services = services;
    this.#lifecycle = lifecycle;
  }
 
  /**
   * Validates an instance like Sequelize v6 `instance.validate()`.
   *
   * @param instance - Instance.
   * @param options - `hooks`, `skip`, `fields`.
   * @returns The instance, when valid (as v6 does at runtime).
   * @throws ValidationError with all failures.
   */
  async validate(instance: AnyModel, options: ValidateOptions): Promise<AnyModel> {
    const model = instance.constructor;
    const state = this.#services.registry.state(model);
    const hooks = options.hooks !== false;
    const skip = this.#skipped(state.definition, options);
    if (hooks) {
      await this.#lifecycle.runHooks(model, 'beforeValidate', instance, options);
    }
    await this.#throwFailures(instance, skip, options);
    if (hooks) {
      await this.#lifecycle.runHooks(model, 'afterValidate', instance, options);
    }
    return instance;
  }
 
  async #throwFailures(
    instance: AnyModel,
    skip: ReadonlySet<string>,
    options: ValidateOptions,
  ): Promise<void> {
    const model = instance.constructor;
    const items = await this.#failures(instance, this.#services.registry.state(model), skip);
    if (items.length === 0) {
      return;
    }
    const error = new ValidationError(null, items);
    if (options.hooks !== false) {
      await this.#lifecycle.runHooks(model, 'validationFailed', instance, options, error);
    }
    throw error;
  }
 
  /**
   * 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.
   */
  async validateAll(instances: readonly AnyModel[], hooks: boolean): Promise<void> {
    const failures = await Promise.all(
      instances.map((instance) =>
        instance.validate({ hooks }).then(
          () => undefined,
          (error: unknown) =>
            new BulkRecordError(
              error instanceof Error ? error : new Error(String(error)),
              instance,
            ),
        ),
      ),
    );
    const errors = failures.filter((failure): failure is BulkRecordError => failure !== undefined);
    Eif (errors.length > 0) {
      throw new AggregateError(errors);
    }
  }
 
  #skipped(definition: ModelDefinition, options: ValidateOptions): ReadonlySet<string> {
    const attributes = [...definition.attributes.keys()];
    return new Set(
      options.skip ??
        (options.fields === undefined
          ? []
          : attributes.filter((name) => !options.fields?.includes(name))),
    );
  }
 
  #failures(
    instance: AnyModel,
    state: ModelState,
    skip: ReadonlySet<string>,
  ): Promise<readonly ValidationErrorItem[]> {
    return this.#services.validator.validate(
      {
        instance,
        definition: state.definition,
        values: instance.dataValues as Readonly<Record<string, unknown>>,
        previous: instance._previousDataValues as Readonly<Record<string, unknown>>,
        isNewRecord: instance.isNewRecord,
      },
      { skip },
      state.validators,
      state.schema,
    );
  }
}