Skip to content

Zod Validator

ts

type ZodValidatorType = "json" | "query" | "param" | "header";
type ZodValidatorSchema = ZodType<any, ZodTypeDef, any>;

export function ZV<T extends ZodValidatorSchema>(
  type: ZodValidatorType,
  schema: T
): MiddlewareHandler {
  return zValidator(type, schema, (result, c) => {
    if (!result.success) {
      console.log("zod result > ", result.error.issues);

      const [first] = result.error.issues;

      // @ts-ignore
      const { path, received, expected } = first;

      const message =
        received === "undefined"
          ? `缺少 ${path?.join("、")}`
          : `${path?.join("、")} 应该为 ${expected}`;

      c.status(400);
      return c.json(nok("PARAM_ERROR", message));
    }
  });
}