All files / src/validators compose.ts

100% Statements 11/11
100% Branches 2/2
100% Functions 2/2
100% Lines 6/6

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  10x                                                 20x     44x 44x 44x   9x    
import { Validator } from "../types";
import { isValid } from "../utils";
 
/**
 * Combines several validators and returns a composed validator
 * that applies all given validators one by one.
 *
 * Stops at first validator returning errors, so you can guard yourself
 * by placing less strict rules first.
 *
 * @example
 *
 * ```ts
 * import { compose, string, minLength } from 'compose-validators';
 *
 * const validate = compose(string, minLength(3));
 *
 * validate([]) // => { type: "string" }
 * validate("") // => { minLength: 3 }
 * validate("abc") // => {}
 * ```
 *
 * @typeParam T expected value type
 *
 * @param validators
 */
export const compose = <T>(...validators: Validator<T>[]): Validator<T> => (
  value: T
) => {
  for (const validator of validators) {
    const result = validator(value);
    if (!isValid(result)) return result;
  }
  return {};
};