DenoDDeno
Powered by
PonchoP
Deno•3y 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));
  },
};
// 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()
req.json()
that throws an error when it doesn't match the
User
User
interface and continues with the code if it does?
Thank you
Deno banner
DenoJoin
Chat about Deno, a modern runtime for JavaScript and TypeScript.
20,934Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Looking for caching API Responses
AlékiAAléki / help
3y ago
Are pointers supported in Fast API return types?
NeTTNNeTT / help
4y ago
[Fresh 2] How to reference DOM types in Islands?
vicaryVvicary / help
6mo ago