79300523

Date: 2024-12-22 05:42:16
Score: 1
Natty:
Report link

I have answered a similar question here - https://stackoverflow.com/a/79300489/15461314, you can take a look. Your code can look like this then -


type ZodInputSchema<T extends keyof ValidationTargets, U extends z.ZodType> = {
  in: {
    [K in T]: z.input<U>;
  };
  out: {
    [K in T]: z.infer<U>;
  };
};

const validationMiddleware = <
  T extends z.ZodSchema,
  U extends keyof ValidationTargets,
  E extends Env,
  P extends string,
  I extends ZodInputSchema<U, T>
>(
  schema: T,
  target: U
) => {
  return createMiddleware<E, P, I>(async (c, next) => {
    await next();
    zValidator(target, schema, (result, c) => {
      if (!result.success) {
        return c.json({
          success: false,
          error: {
            code: 400,
            message: result.error.issues[0].message,
            innerError: {
              timestamp: new Date(Date.now()),
            },
          },
        });
      }
    });
  });
};

// Usage
app.get("/sample", validationMiddleware(schema, "json"));
Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Aditya Mathur