Poncho
Poncho6mo ago

How to validate types in API Requests and Responses?

Hello, I'm wondering how to validate and handle the types in my app's API. I'll use the example found in the docs as an example:
// routes/api/users/index.ts
export const handler: Handlers<User | null> = {
async POST(req, _ctx) {
const user = (await req.json()) as User;
const userKey = ["user", user.id];
const ok = await kv.atomic().set(userKey, user).commit();
if (!ok) throw new Error("Something went wrong.");
return new Response(JSON.stringify(user));
},
};
// routes/api/users/index.ts
export const handler: Handlers<User | null> = {
async POST(req, _ctx) {
const user = (await req.json()) as User;
const userKey = ["user", user.id];
const ok = await kv.atomic().set(userKey, user).commit();
if (!ok) throw new Error("Something went wrong.");
return new Response(JSON.stringify(user));
},
};
How to add a type validator for the object req.json() that throws an error when it doesn't match the User interface and continues with the code if it does? Thank you
2 Replies
raunioroo
raunioroo6mo ago
I've heard folks like to use Zod for that. No personal experience though. https://zod.dev/
GitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
Poncho
Poncho6mo ago
Thanks for your answer, but my issue with Zod is that one must create a schema different from the already used interfaces like the User interface in the example.