All files / server/src/utils zodUtils.ts

100% Statements 9/9
80% Branches 4/5
100% Functions 3/3
100% Lines 9/9

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        44x         440x 2406x 2118x   288x 570x   288x 288x   288x      
import z from "zod";
import { partition } from "remeda";
import { logger } from "server/utils/logger";
 
export const safeEnumArray = <T extends Record<string, string>>(
  enumType: T,
  label: string,
  fallback: T[keyof T][] = [],
): z.ZodCatch<z.ZodArray<z.ZodEnum<T>>> => {
  return z.array(z.enum(enumType)).catch((ctx) => {
    if (!Array.isArray(ctx.value)) {
      return fallback;
    }
    const [valid, invalid] = partition(ctx.value as string[], (val) =>
      Object.values(enumType).includes(val),
    );
    Eif (invalid.length > 0) {
      logger.error(new Error(`Invalid ${label}: ${JSON.stringify(invalid)}`));
    }
    return valid as T[keyof T][];
  });
};