Last active
May 6, 2024 13:50
-
-
Save sidouglas/ce5e01a8038a06d514d71abbb6139da0 to your computer and use it in GitHub Desktop.
Using Fetch with Zod in a 2 step request Factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { ZodTypeAny, z } from 'zod'; | |
//@see https://zod.dev/?id=writing-generic-functions | |
export const createFetch = <Output extends ZodTypeAny>( | |
zodSchema: Output | |
): ((input: RequestInfo | URL, init?: RequestInit) => Promise<z.infer<Output>>) => { | |
return (input, init) => | |
fetch(input, init).then((res) => { | |
if (!res.ok) { | |
throw new Error(res.statusText); | |
} | |
return res.json().then((data: unknown) => { | |
const result = zodSchema.safeParse(data); | |
if (result.success) { | |
return result.data as z.infer<Output>; | |
} else { | |
throw result.error.format(); | |
} | |
}); | |
}); | |
}; |
Author
sidouglas
commented
Apr 24, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment