All files / src/validation builtin-attribute-validator.ts

100% Statements 26/26
97.43% Branches 38/39
100% Functions 8/8
100% Lines 26/26

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          131x                                           76x 2x   74x 74x 1x   73x 73x 73x                     1x                                 21x                                     73x 2x   71x       73x 57x   16x 16x       37x                       73x     73x 25x   48x 2x   46x       46x            
import { ValidationErrorItem } from '../errors/errors.ts';
import type { AttributeDefinition } from '../model/model-definition.ts';
import { BuiltinValidators } from './builtin-validators.ts';
import type { ValidationTarget } from './validation-target.ts';
 
const builtinValidators = new BuiltinValidators();
 
/** Runs one built-in (validator.js) validator option of an attribute. */
export class BuiltinAttributeValidator {
  /**
   * Validates a non-null attribute value.
   *
   * @param target - Instance being validated.
   * @param attribute - Attribute definition.
   * @param name - Validator name, e.g. `isEmail`.
   * @param test - Validator option: `false`, arguments, or `{ args, msg }`.
   * @param value - Current value of the attribute.
   * @returns The failure, or `undefined` when the value passed or the validator is disabled.
   * @remarks An unknown validator name fails with `Invalid validator function: <name>`, like v6.
   */
  run(
    target: ValidationTarget,
    attribute: AttributeDefinition,
    name: string,
    test: unknown,
    value: unknown,
  ): ValidationErrorItem | undefined {
    if (test === false) {
      return undefined;
    }
    const field = attribute.fieldName;
    if (name !== 'isImmutable' && builtinValidators.find(name) === undefined) {
      return this.#unknown(target, field, name, value);
    }
    const normalized = BuiltinAttributeValidator.#normalize(name, test);
    const args = BuiltinAttributeValidator.#args(normalized, name, field, target);
    return BuiltinAttributeValidator.#passes(target, field, name, args, value)
      ? undefined
      : BuiltinAttributeValidator.#failure(target, field, name, normalized, args, value);
  }
 
  #unknown(
    target: ValidationTarget,
    field: string,
    name: string,
    value: unknown,
  ): ValidationErrorItem {
    return new ValidationErrorItem(
      `Invalid validator function: ${name}`,
      'Validation error',
      field,
      value,
      target.instance,
    );
  }
 
  static #failure(
    target: ValidationTarget,
    field: string,
    name: string,
    test: unknown,
    args: readonly unknown[],
    value: unknown,
  ): ValidationErrorItem {
    return new ValidationErrorItem(
      BuiltinAttributeValidator.#message(test) ?? `Validation ${name} on ${field} failed`,
      'Validation error',
      field,
      value,
      target.instance,
      name,
      name,
      args,
    );
  }
 
  static #passes(
    target: ValidationTarget,
    field: string,
    name: string,
    args: readonly unknown[],
    value: unknown,
  ): boolean {
    if (name === 'isImmutable') {
      return target.isNewRecord || target.values[field] === target.previous[field];
    }
    return builtinValidators.find(name)?.(String(value), ...args) ?? false;
  }
 
  static #normalize(name: string, test: unknown): unknown {
    if (!['isUrl', 'isURL', 'isEmail'].includes(name)) {
      return test;
    }
    const msg = BuiltinAttributeValidator.#message(test);
    return msg === undefined ? {} : { msg };
  }
 
  static #message(test: unknown): string | undefined {
    return typeof test === 'object' && test !== null && 'msg' in test
      ? String((test as { msg: unknown }).msg)
      : undefined;
  }
 
  static #args(
    test: unknown,
    name: string,
    field: string,
    target: ValidationTarget,
  ): readonly unknown[] {
    const raw =
      typeof test === 'object' && test !== null && 'args' in test
        ? (test as { args: unknown }).args
        : test;
    if (Array.isArray(raw)) {
      return raw;
    }
    if (name === 'isImmutable') {
      return [raw, field, target];
    }
    return BuiltinAttributeValidator.#takesNoArgs(raw, name) ? [] : [raw];
  }
 
  static #takesNoArgs(raw: unknown, name: string): boolean {
    return (
      (typeof raw !== 'string' && ['isAlpha', 'isAlphanumeric', 'isMobilePhone'].includes(name)) ||
      name === 'isIP'
    );
  }
}