elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

Wretch with Zod #186

Closed viclafouch closed 1 year ago

viclafouch commented 1 year ago

Hello !

I'm trying to use wretch with zod in order to validate my schema on request, is there an example somewhere ?

Like: Do the request => validate schema => return the JSON with the correct typing. Would be nice to have something in the documentation for any schema validation libraries

elbywan commented 1 year ago

Hey @viclafouch,

I'm trying to use wretch with zod in order to validate my schema on request, is there an example somewhere ?

I am not super familiar with zod (never used it) but I had a try and it seemed to be kinda straightforward. Here is an example:

import wretch from 'wretch';
import z from "zod"

const Todo = z.object({
  userId: z.number(),
  id: z.number(),
  title: z.string(),
  completed: z.boolean()
});

type Todo = z.infer<typeof Todo>

const todo = await wretch("https://jsonplaceholder.typicode.com/todos/1")
  .get()
  .json(Todo.parse)
  .catch(console.error)

console.log(todo)

Would be nice to have something in the documentation for any schema validation libraries

I understand but since every library has its own special syntax it feels like it would be a lot of effort - ultimately not worth it IMO.

viclafouch commented 1 year ago

Got it ! Thanks @elbywan