All files / validator/src chain.ts

100% Statements 7/7
100% Branches 2/2
100% Functions 4/4
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 331x 1x                                     2x     2x 3x   9x            
import { pipe } from "@benneq/function";
import { flatMap, limit } from "@benneq/iterable";
import { ConstraintViolation, Validator } from "./_types";
 
/**
 *
 * @example
 * Check if `value` is positive and even
 * ```ts
 * const chainedValidator = validate(chain(
 *   valueValidator(isPositive, "err1"),
 *   valueValidator(isEven, "err2")
 * ));
 * const result = chainedValidator(-1);
 * console.log(result); // [{ path: "$", message: "err1", value: -1 }]
 * ```
 *
 * @param validators
 * @returns
 */
export const chain = <T, R = T, P = unknown>(
  ...validators: Validator<T, R, P>[]
): Validator<T, R, P> => {
  return (value, context) => {
    return pipe(
      flatMap<Validator<T, R, P>, ConstraintViolation>((validator) =>
        validator(value, context)
      ),
      limit<ConstraintViolation>(context.shortCircuit ? 1 : -1)
    )(validators);
  };
};