All files / src/validation attribute-validators.ts

100% Statements 29/29
92% Branches 23/25
100% Functions 11/11
100% Lines 29/29

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                  131x       131x 131x 131x                             90x 1x   89x 89x                   16842x       16931x 16931x   245x                 89x 121x   89x                   121x 6x   115x 11x   104x                 6x                       11x 11x 6x               11x                   104x 28x   76x 76x      
import { ValidationErrorItem } from '../errors/errors.ts';
import type { AttributeDefinition } from '../model/model-definition.ts';
import { BuiltinAttributeValidator } from './builtin-attribute-validator.ts';
import { CustomValidators } from './custom-validators.ts';
import { SchemaItems } from './schema-items.ts';
import type { StandardSchemaV1 } from './standard-schema.ts';
import type { AttributeValidateOptions } from './types.ts';
import type { ValidationTarget } from './validation-target.ts';
 
const NO_ITEMS: Promise<readonly ValidationErrorItem[]> = Promise.resolve([]);
 
/** Runs the `validate` options of one attribute: built-in, custom and Standard Schema validators. */
export class AttributeValidators {
  readonly #builtin = new BuiltinAttributeValidator();
  readonly #custom = new CustomValidators();
  readonly #schema = new SchemaItems();
 
  /**
   * Validates one attribute value (`notNull` is checked elsewhere).
   *
   * @param target - Instance being validated.
   * @param attribute - Attribute definition.
   * @param value - Current value of the attribute.
   * @returns Failures of all validators of the attribute.
   */
  items(
    target: ValidationTarget,
    attribute: AttributeDefinition,
    value: unknown,
  ): Promise<readonly ValidationErrorItem[]> {
    if ((value === null || value === undefined) && attribute.allowNull === false) {
      return NO_ITEMS;
    }
    const tests = AttributeValidators.#tests(attribute);
    return tests.length === 0 ? NO_ITEMS : this.#run(target, attribute, tests, value);
  }
 
  /**
   * Whether the attribute has validators to run (everything in `validate` except `notNull`).
   *
   * @param attribute - Attribute definition.
   * @returns True when {@link AttributeValidators.items} can report failures.
   */
  hasValidators(attribute: AttributeDefinition): boolean {
    return AttributeValidators.#tests(attribute).length > 0;
  }
 
  static #tests(attribute: AttributeDefinition): readonly (readonly [string, unknown])[] {
    const validate = attribute.validate as AttributeValidateOptions | undefined;
    return validate === undefined
      ? []
      : Object.entries(validate).filter(([name]) => name !== 'notNull');
  }
 
  async #run(
    target: ValidationTarget,
    attribute: AttributeDefinition,
    tests: readonly (readonly [string, unknown])[],
    value: unknown,
  ): Promise<readonly ValidationErrorItem[]> {
    const results = await Promise.all(
      tests.map(([name, test]) => this.#validatorItems(target, attribute, name, test, value)),
    );
    return results.flat();
  }
 
  async #validatorItems(
    target: ValidationTarget,
    attribute: AttributeDefinition,
    name: string,
    test: unknown,
    value: unknown,
  ): Promise<readonly ValidationErrorItem[]> {
    if (name === 'schema' && this.#schema.isSchema(test)) {
      return this.#schemaItems(target, attribute.fieldName, test, value);
    }
    if (typeof test === 'function') {
      return this.#customItems(target, attribute, name, test, value);
    }
    return this.#builtinItems(target, attribute, name, test, value);
  }
 
  #schemaItems(
    target: ValidationTarget,
    path: string,
    schema: StandardSchemaV1,
    value: unknown,
  ): Promise<readonly ValidationErrorItem[]> {
    return value === undefined
      ? Promise.resolve([])
      : this.#schema.items(target, schema, value, path);
  }
 
  async #customItems(
    target: ValidationTarget,
    attribute: AttributeDefinition,
    name: string,
    fn: unknown,
    value: unknown,
  ): Promise<readonly ValidationErrorItem[]> {
    const failure = await this.#custom.failure(target.instance, fn, [value]);
    const item = (message: string): ValidationErrorItem =>
      new ValidationErrorItem(
        message,
        'Validation error',
        attribute.fieldName,
        value,
        target.instance,
        name,
      );
    return failure === undefined ? [] : [item(failure.message).withOriginal(failure.original)];
  }
 
  #builtinItems(
    target: ValidationTarget,
    attribute: AttributeDefinition,
    name: string,
    test: unknown,
    value: unknown,
  ): readonly ValidationErrorItem[] {
    if (value === null || value === undefined) {
      return [];
    }
    const item = this.#builtin.run(target, attribute, name, test, value);
    return item === undefined ? [] : [item];
  }
}