PonchoP
Deno2y ago
2 replies
Poncho

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));
  },
};


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
Was this page helpful?