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"));