File
Blob: src/worker/lib/validate.ts
| 1 | import type { Context } from "hono"; |
| 2 | import type { z } from "zod"; |
| 3 | |
| 4 | /** |
| 5 | * Parse the JSON body against a Zod schema. |
| 6 | * Returns the parsed data, or a 400 Response if validation fails. |
| 7 | */ |
| 8 | export async function parseBody<T extends z.ZodType>(c: Context, schema: T): Promise<z.infer<T> | Response> { |
| 9 | let raw: unknown; |
| 10 | try { |
| 11 | raw = await c.req.json(); |
| 12 | } catch { |
| 13 | return c.json({ error: "invalid_json", message: "Request body is not valid JSON" }, 400); |
| 14 | } |
| 15 | const body = schema.safeParse(raw); |
| 16 | if (!body.success) { |
| 17 | return c.json({ error: "validation_error", message: body.error.issues[0].message, issues: body.error.issues }, 400); |
| 18 | } |
| 19 | return body.data; |
| 20 | } |