All files / src index.ts

97.72% Statements 43/44
90.9% Branches 30/33
100% Functions 7/7
100% Lines 37/37

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        16x 16x       16x 16x             16x 23x   23x   23x 23x 23x 23x   23x 16x   15x 19x 1x 2x   2x   1x     18x   18x   10x     7x 7x 1x 2x           6x 5x                   16x       2x   2x   1x       4x       2x                                                       3x 3x       2x            
export class Validator<T extends object> {
  private config: Validator.Config<T>;
  private strict: boolean;
  constructor(config: Validator.Config<T>, strict: boolean = false) {
    this.config = config;
    this.strict = strict;
  }
 
  check(thing: object): string[] {
    const errors: string[] = [];
    const stack: Validator.StackItem[] = [
      {
        item: thing,
        config: this.config,
      },
    ];
 
    while (stack.length !== 0) {
      const { parentKey, item, config } = stack.shift() ?? {};
 
      Iif (!config) continue;
 
      for (const key in config) {
        const configItem = config[key];
        const innerValue = item && key in item ? item[key as keyof typeof item] : null;
        const innerKey = parentKey ? `${parentKey}.${key}` : key;
 
        if (Array.isArray(configItem)) {
          if (configItem.length === 0) continue;
 
          for (const validator of configItem) {
            if (Array.isArray(innerValue)) {
              for (let i = 0; i < innerValue.length; i++) {
                const error = validator(innerValue[i]);
 
                if (!error) continue;
 
                errors.push(`"${innerKey}[${i}]" ${error}`);
              }
            } else {
              const error = validator(item ? item[key] : null);
 
              if (!error) continue;
 
              errors.push(`"${innerKey}" ${error}`);
            }
          }
        } else if (Etypeof configItem === 'object') {
          if (Array.isArray(innerValue)) {
            for (let i = 0; i < innerValue.length; i++) {
              stack.push({
                parentKey: `${innerKey}[${i}]`,
                item: innerValue[i],
                config: configItem,
              });
            }
          } else if (this.strict || innerValue) {
            stack.push({
              parentKey: innerKey,
              item: innerValue,
              config: configItem,
            });
          }
        }
      }
    }
 
    return errors;
  }
 
  validate(thing: object): asserts thing is T {
    const errors = this.check(thing);
 
    if (errors.length === 0) return;
 
    throw new ValidationError(errors);
  }
 
  isValid(thing: object): thing is T {
    return this.check(thing).length === 0;
  }
 
  isInvalid<V extends object>(thing: V): thing is Exclude<V, T> {
    return !this.isValid(thing);
  }
}
 
export namespace Validator {
  export type Fn<T> = (value: T) => string | void;
 
  export type Config<T extends object> = {
    [key in keyof T]?: T[key] extends Array<object>
      ? Config<T[key][number]>
      : T[key] extends Array<unknown>
        ? Fn<T[key][number]>[]
        : T[key] extends object
          ? Config<T[key]>
          : Fn<T[key]>[];
  };
 
  export type StackItem = {
    parentKey?: string;
    item: any;
    config: Config<any>;
  };
}
 
export class ValidationError extends Error {
  errors: string[];
 
  constructor(errors: string[]) {
    super(errors.join('\n'));
    this.errors = errors;
  }
 
  toString() {
    return this.errors.join('\n');
  }
}
 
export * from './validators';
export * from './utils';