Skip to content

Instantly share code, notes, and snippets.

@ph3b
Last active April 5, 2024 21:11
Show Gist options
  • Save ph3b/5afc53bcefeed9630911a0585ca6529f to your computer and use it in GitHub Desktop.
Save ph3b/5afc53bcefeed9630911a0585ca6529f to your computer and use it in GitHub Desktop.
itty-router + zod query validation
import { RequestHandler, IRequest, json } from "itty-router";
import { z } from "zod";
export const zodQuery =
<T extends z.ZodRawShape>(
rawShape: T
): RequestHandler<
IRequest & { data: z.infer<z.ZodObject<typeof rawShape>> }
> =>
(request) => {
request.data = z.object(rawShape).parse(request.query);
};
router.get("/message", zodQuery({ name: z.string(), age: z.number() }), (req) => {
const { name, age } = req.data // Is now validated and typed
return json({ name, age })
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment