Skip to content

Instantly share code, notes, and snippets.

@sidouglas
Last active May 6, 2024 13:50
Show Gist options
  • Save sidouglas/ce5e01a8038a06d514d71abbb6139da0 to your computer and use it in GitHub Desktop.
Save sidouglas/ce5e01a8038a06d514d71abbb6139da0 to your computer and use it in GitHub Desktop.
Using Fetch with Zod in a 2 step request Factory
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();
}
});
});
};
@sidouglas
Copy link
Author

sidouglas commented Apr 24, 2024

// inside an async fn: 
const get = createFetch<typeof YOUR_ZOD_SCHEMA_OBJECT>(YOUR_ZOD_SCHEMA_OBJECT);
try {
  const result = await get('/some-url')
  // carry on you have the parsed data now
} catch(e) {  // deal with it }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment