All files / src/validation instance-validator.ts

100% Statements 25/25
100% Branches 7/7
100% Functions 15/15
100% Lines 25/25

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                                          131x 131x 131x 131x                                 3435x 3435x 3435x         3435x       3435x   18356x                 3435x 16842x               3435x   16842x   90x     3435x             3435x                   3435x   22x 22x   3435x               22x 22x                             3x 18x        
import { ValidationErrorItem } from '../errors/errors.ts';
import { SqlExpression } from '../expressions/methods.ts';
import type { AttributeDefinition } from '../model/model-definition.ts';
import { AttributeValidators } from './attribute-validators.ts';
import { CoreValidator } from './core-validator.ts';
import { CustomValidators } from './custom-validators.ts';
import type { StandardSchemaV1 } from './standard-schema.ts';
import { SchemaItems } from './schema-items.ts';
import type { ModelValidatorFunction } from './types.ts';
import type { ValidationScope, ValidationTarget } from './validation-target.ts';
 
export type { ValidationScope, ValidationTarget } from './validation-target.ts';
 
/**
 * Validates instances like Sequelize v6 `InstanceValidator` (without hooks): `notNull`, string
 * values, built-in (validator.js) and custom attribute validators, Standard Schemas and model
 * validators. Expressions (`literal`, `fn`, ...) are not validated.
 *
 * @internal
 */
export class InstanceValidator {
  readonly #core = new CoreValidator();
  readonly #attributes = new AttributeValidators();
  readonly #schema = new SchemaItems();
  readonly #custom = new CustomValidators();
 
  /**
   * Validates an instance and returns all failures.
   *
   * @param target - Instance, its definition and values.
   * @param scope - Attributes and model validators to skip.
   * @param modelValidators - Model-level validators (`validate` model option).
   * @param modelSchema - Standard Schema of the whole model (`schema` model option).
   * @returns Failures; empty when the instance is valid.
   */
  async validate(
    target: ValidationTarget,
    scope: ValidationScope,
    modelValidators: Readonly<Record<string, ModelValidatorFunction>> = {},
    modelSchema?: StandardSchemaV1,
  ): Promise<readonly ValidationErrorItem[]> {
    const attributes = this.#checked(target, scope);
    const coreErrors = this.#coreItems(target, attributes);
    const [attributeErrors, modelErrors, schemaIssues] = await Promise.all([
      this.#attributeItems(target, attributes),
      this.#modelValidatorItems(target, modelValidators, scope),
      this.#modelSchemaItems(target, modelSchema),
    ]);
    return [...coreErrors, ...attributeErrors, ...modelErrors, ...schemaIssues];
  }
 
  #checked(target: ValidationTarget, scope: ValidationScope): readonly AttributeDefinition[] {
    return [...target.definition.attributes.values()].filter(
      (attribute) =>
        !scope.skip.has(attribute.fieldName) &&
        !(target.values[attribute.fieldName] instanceof SqlExpression),
    );
  }
 
  #coreItems(
    target: ValidationTarget,
    attributes: readonly AttributeDefinition[],
  ): readonly ValidationErrorItem[] {
    return attributes.flatMap((attribute) =>
      this.#core.items(target, attribute, target.values[attribute.fieldName]),
    );
  }
 
  async #attributeItems(
    target: ValidationTarget,
    attributes: readonly AttributeDefinition[],
  ): Promise<readonly ValidationErrorItem[]> {
    const results = await Promise.all(
      attributes
        .filter((attribute) => this.#attributes.hasValidators(attribute))
        .map((attribute) =>
          this.#attributes.items(target, attribute, target.values[attribute.fieldName]),
        ),
    );
    return results.flat();
  }
 
  #modelSchemaItems(
    target: ValidationTarget,
    schema: StandardSchemaV1 | undefined,
  ): Promise<readonly ValidationErrorItem[]> {
    return schema === undefined
      ? Promise.resolve([])
      : this.#schema.items(target, schema, this.#plainValues(target), undefined);
  }
 
  async #modelValidatorItems(
    target: ValidationTarget,
    validators: Readonly<Record<string, ModelValidatorFunction>>,
    scope: ValidationScope,
  ): Promise<readonly ValidationErrorItem[]> {
    const results = await Promise.all(
      Object.entries(validators)
        .filter(([name]) => !scope.skip.has(name))
        .map(([name, fn]) => this.#modelItems(target, name, fn)),
    );
    return results.flat();
  }
 
  async #modelItems(
    target: ValidationTarget,
    name: string,
    fn: ModelValidatorFunction,
  ): Promise<readonly ValidationErrorItem[]> {
    const failure = await this.#custom.failure(target.instance, fn, []);
    return failure === undefined
      ? []
      : [
          new ValidationErrorItem(
            failure.message,
            'Validation error',
            name,
            null,
            target.instance,
            name,
          ).withOriginal(failure.original),
        ];
  }
 
  #plainValues(target: ValidationTarget): Readonly<Record<string, unknown>> {
    return Object.fromEntries(
      [...target.definition.attributes.keys()].map((name) => [name, target.values[name]]),
    );
  }
}