( schema: TResponseBodySchema, url: string, requestInit?: PromiseOrValue<RequestInit>, options?: ZodFetchOptions, attempt = 1 )
| 175 | type PromiseOrValue<T> = T | Promise<T>; |
| 176 | |
| 177 | async function _doZodFetch<TResponseBodySchema extends z.ZodTypeAny>( |
| 178 | schema: TResponseBodySchema, |
| 179 | url: string, |
| 180 | requestInit?: PromiseOrValue<RequestInit>, |
| 181 | options?: ZodFetchOptions, |
| 182 | attempt = 1 |
| 183 | ): Promise<ZodFetchResult<z.output<TResponseBodySchema>>> { |
| 184 | try { |
| 185 | const $requestInit = await requestInit; |
| 186 | |
| 187 | const response = await fetch(url, requestInitWithCache($requestInit)); |
| 188 | |
| 189 | const responseHeaders = createResponseHeaders(response.headers); |
| 190 | |
| 191 | if (!response.ok) { |
| 192 | const retryResult = shouldRetry(response, attempt, options?.retry); |
| 193 | |
| 194 | if (retryResult.retry) { |
| 195 | await new Promise((resolve) => setTimeout(resolve, retryResult.delay)); |
| 196 | |
| 197 | return await _doZodFetch(schema, url, requestInit, options, attempt + 1); |
| 198 | } else { |
| 199 | const errText = await response.text().catch((e) => castToError(e).message); |
| 200 | const errJSON = safeJsonParse(errText); |
| 201 | const errMessage = errJSON ? undefined : errText; |
| 202 | |
| 203 | throw ApiError.generate(response.status, errJSON, errMessage, responseHeaders); |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | const jsonBody = await response.json(); |
| 208 | const parsedResult = schema.safeParse(jsonBody); |
| 209 | |
| 210 | if (parsedResult.success) { |
| 211 | return { data: parsedResult.data, response }; |
| 212 | } |
| 213 | |
| 214 | throw fromZodError(parsedResult.error); |
| 215 | } catch (error) { |
| 216 | if (error instanceof ApiError) { |
| 217 | throw error; |
| 218 | } |
| 219 | |
| 220 | if (options?.retry) { |
| 221 | const retry = { ...defaultRetryOptions, ...options.retry }; |
| 222 | |
| 223 | const delay = calculateNextRetryDelay(retry, attempt); |
| 224 | |
| 225 | if (delay) { |
| 226 | await new Promise((resolve) => setTimeout(resolve, delay)); |
| 227 | |
| 228 | return await _doZodFetch(schema, url, requestInit, options, attempt + 1); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | throw new ApiConnectionError({ cause: castToError(error) }); |
| 233 | } |
| 234 | } |
no test coverage detected
searching dependent graphs…