( schema: z.Schema<TResponseBody>, url: string, requestInit?: RequestInit )
| 1 | import { z } from "zod"; |
| 2 | |
| 3 | export async function zodfetch<TResponseBody extends any>( |
| 4 | schema: z.Schema<TResponseBody>, |
| 5 | url: string, |
| 6 | requestInit?: RequestInit |
| 7 | ): Promise<TResponseBody> { |
| 8 | const response = await fetch(url, requestInit); |
| 9 | |
| 10 | if ((!requestInit || requestInit.method === "GET") && response.status === 404) { |
| 11 | // @ts-ignore |
| 12 | return; |
| 13 | } |
| 14 | |
| 15 | //todo improve error handling |
| 16 | |
| 17 | if (response.status >= 400 && response.status < 500) { |
| 18 | const body = await response.json(); |
| 19 | |
| 20 | throw new Error(body.error); |
| 21 | } |
| 22 | |
| 23 | if (response.status !== 200) { |
| 24 | throw new Error(`Failed to fetch ${url}, got status code ${response.status}`); |
| 25 | } |
| 26 | |
| 27 | const jsonBody = await response.json(); |
| 28 | |
| 29 | return schema.parse(jsonBody); |
| 30 | } |
no test coverage detected
searching dependent graphs…