All files / src/errors validation-errors.ts

100% Statements 30/30
78.26% Branches 36/46
100% Functions 8/8
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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259                                                          133x             133x             133x             133x   133x       59x 59x                                                                                                                                             59x 59x 59x 59x 59x 59x 59x 59x                     8x 8x                                                             38x       44x     38x 38x                                         4x                                                                                   16x 16x 16x 16x 16x 16x 16x      
import { BaseError, type DriverError } from './base-error.ts';
import type { ConstraintErrorOptions } from './database-errors.ts';
 
/** Origin of a validation error item. */
export type ValidationErrorItemOrigin = 'CORE' | 'DB' | 'FUNCTION';
 
/** Shape of {@link ValidationErrorItemOrigin}. */
export interface ValidationErrorItemOrigins {
  /** Raised by a built-in check such as not-null. */
  readonly CORE: 'CORE';
  /** Raised by the database, e.g. a unique violation. */
  readonly DB: 'DB';
  /** Raised by a custom validator function. */
  readonly FUNCTION: 'FUNCTION';
}
 
/** Shape of {@link ValidationErrorItemType}. */
export interface ValidationErrorItemTypes {
  /** A not-null violation is a `CORE` error. */
  readonly 'notnull violation': 'CORE';
  /** A string violation is a `CORE` error. */
  readonly 'string violation': 'CORE';
  /** A unique violation is a `DB` error. */
  readonly 'unique violation': 'DB';
  /** A failed validator is a `FUNCTION` error. */
  readonly 'validation error': 'FUNCTION';
}
 
/** Values of {@link ValidationErrorItem.origin}, as in Sequelize v6. */
export const ValidationErrorItemOrigin: ValidationErrorItemOrigins = Object.freeze({
  CORE: 'CORE',
  DB: 'DB',
  FUNCTION: 'FUNCTION',
});
 
/** Origin by validation error type, as in Sequelize v6 (`ValidationErrorItemType['unique violation']` is `'DB'`). */
export const ValidationErrorItemType: ValidationErrorItemTypes = Object.freeze({
  'notnull violation': 'CORE',
  'string violation': 'CORE',
  'unique violation': 'DB',
  'validation error': 'FUNCTION',
});
 
const ORIGIN_BY_TYPE: Readonly<Record<string, ValidationErrorItemOrigin>> = {
  'notnull violation': 'CORE',
  'string violation': 'CORE',
  'unique violation': 'DB',
  'validation error': 'FUNCTION',
};
 
const ORIGINS: ReadonlySet<string> = new Set(['CORE', 'DB', 'FUNCTION']);
 
const classify = (
  type: string | null | undefined,
): Readonly<{ origin: ValidationErrorItemOrigin | null; type: string | null }> => {
  const origin =
    type === undefined || type === null ? undefined : ORIGIN_BY_TYPE[type.toLowerCase().trim()];
  return {
    origin:
      type !== undefined && type !== null && ORIGINS.has(type)
        ? (type as ValidationErrorItemOrigin)
        : (origin ?? null),
    type: origin === undefined ? null : (type ?? null),
  };
};
 
/**
 * Describes a single failed validation: which attribute, which value and which validator (Sequelize v6 `ValidationErrorItem`).
 *
 * `origin` is derived from `type`: `'CORE'` for not-null and string violations, `'DB'` for unique violations, `'FUNCTION'` for custom validators.
 *
 * @example
 * ```ts
 * try {
 *   await User.create({ email: 'not-an-email' });
 * } catch (e) {
 *   if (e instanceof ValidationError) {
 *     for (const item of e.errors) {
 *       console.error(item.path, item.validatorKey, item.value, item.origin);
 *     }
 *   }
 * }
 * ```
 */
export class ValidationErrorItem {
  /** Human-readable message. */
  readonly message: string;
  /** Validation type, e.g. `'unique violation'`, `'notNull Violation'`, `'Validation error'`. */
  declare readonly type: string | null;
  /** Attribute name (or model validator name). */
  readonly path: string | null;
  /** Offending value. */
  readonly value: unknown;
  /** Where the error was raised, derived from `type`. */
  declare readonly origin: ValidationErrorItemOrigin | null;
  /** Instance being validated. */
  readonly instance: object | null;
  /** Validator key, e.g. `'not_unique'`, `'is_null'`, `'isEmail'`. */
  readonly validatorKey: string | null;
  /** Built-in validator name. */
  readonly validatorName: string | null;
  /** Built-in validator arguments. */
  readonly validatorArgs: readonly unknown[];
  /** What a custom validator threw (v6 `original`); set only on items of failed custom validators. */
  original?: unknown;
 
  /**
   * Creates an item; `path`, `instance`, `validatorKey` and `validatorName` default to `null`, `validatorArgs` to `[]`, and `value` to `null` when `undefined`.
   *
   * @param message - Human-readable message.
   * @param type - Validation type or origin.
   * @param path - Attribute name.
   * @param value - Offending value.
   * @param instance - Instance being validated.
   * @param validatorKey - Validator key.
   * @param validatorName - Built-in validator name.
   * @param validatorArgs - Built-in validator arguments.
   */
  constructor(
    message: string,
    type?: string | null,
    path?: string | null,
    value?: unknown,
    instance?: object | null,
    validatorKey?: string | null,
    validatorName?: string | null,
    validatorArgs?: readonly unknown[],
  ) {
    this.message = message;
    this.path = path ?? null;
    this.value = value === undefined ? null : value;
    this.instance = instance ?? null;
    this.validatorKey = validatorKey ?? null;
    this.validatorName = validatorName ?? null;
    this.validatorArgs = validatorArgs ?? [];
    Object.assign(this, classify(type));
  }
 
  /**
   * Records what a custom validator threw as {@link ValidationErrorItem.original}.
   *
   * @internal
   * @param original - The thrown value.
   * @returns This item.
   */
  withOriginal(original: unknown): this {
    this.original = original;
    return this;
  }
}
 
/**
 * Thrown when a model instance fails validation, carrying one item per failed rule (Sequelize v6 `ValidationError`).
 *
 * Raised by `create`, `save`, `update`, `build(...).validate()` and similar before any SQL is sent. Not-null, unique and validator failures all end up in `errors`.
 *
 * @example
 * ```ts
 * try {
 *   await User.create({ email: 'not-an-email' });
 * } catch (e) {
 *   if (e instanceof ValidationError) {
 *     console.error(e.errors.map((item) => `${item.path}: ${item.message}`));
 *   }
 * }
 * ```
 */
export class ValidationError extends BaseError {
  /** Individual validation failures. */
  readonly errors: readonly ValidationErrorItem[];
 
  /**
   * Creates the error from a message and its items.
   *
   * @param message - Error message; when empty it is built from the items like Sequelize v6.
   * @param errors - Individual validation failures.
   */
  constructor(message: string | null | undefined, errors: readonly ValidationErrorItem[] = []) {
    super(
      message !== null && message !== undefined && message !== ''
        ? message
        : errors.length > 0
          ? errors.map((item) => `${item.type ?? item.origin ?? ''}: ${item.message}`).join(',\n')
          : 'Validation Error',
    );
    this.name = 'SequelizeValidationError';
    this.errors = errors;
  }
 
  /**
   * Returns the validation items reported for one attribute.
   *
   * @param path - Attribute name, compared with each item's `path`.
   * @returns Items whose `path` equals `path`; an empty array when there are none.
   *
   * @example
   * ```ts
   * try {
   *   await User.create({});
   * } catch (e) {
   *   if (e instanceof ValidationError) {
   *     console.error(e.get('email').map((item) => item.message));
   *   }
   * }
   * ```
   */
  get(path: string): ValidationErrorItem[] {
    return this.errors.filter((item) => item.path === path);
  }
}
 
/**
 * Thrown when PostgreSQL reports a unique violation (SQLSTATE `23505`); a {@link ValidationError} subclass like in Sequelize v6.
 *
 * `fields` maps the unique columns to the offending values (parsed from the PostgreSQL detail) and `errors` has one `not_unique` item per column.
 *
 * @example
 * ```ts
 * try {
 *   await User.create({ email: 'taken@example.com' });
 * } catch (e) {
 *   if (e instanceof UniqueConstraintError) {
 *     console.error(e.fields, e.errors[0]?.message);
 *   }
 * }
 * ```
 */
export class UniqueConstraintError extends ValidationError {
  /** Original driver error. */
  readonly parent: DriverError;
  /** Original driver error (alias of `parent`). */
  readonly original: DriverError;
  /** Executed SQL text. */
  readonly sql: string;
  /** Unique columns mapped to offending values. */
  readonly fields: Readonly<Record<string, string>>;
 
  /**
   * Builds the error; the message defaults to `Validation error`.
   *
   * @param options - Driver error, fields and validation items.
   */
  constructor(
    options: Omit<ConstraintErrorOptions, 'fields'> &
      Readonly<{
        fields?: Readonly<Record<string, string>>;
        errors?: readonly ValidationErrorItem[];
      }>,
  ) {
    super(options.message ?? 'Validation error', options.errors);
    this.name = 'SequelizeUniqueConstraintError';
    const parent = options.parent ?? Object.assign(new Error(''), { sql: '' });
    this.parent = parent;
    this.original = parent;
    this.sql = options.sql ?? '';
    this.fields = options.fields ?? {};
  }
}