Last active
April 5, 2024 21:11
-
-
Save ph3b/5afc53bcefeed9630911a0585ca6529f to your computer and use it in GitHub Desktop.
itty-router + zod query validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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