|
| 1 | +import fetchRetry from "fetch-retry"; |
| 2 | + |
| 3 | +interface MakeSolidFetchOptions { |
| 4 | + /** |
| 5 | + * return false if the response should be retried |
| 6 | + */ |
| 7 | + verifyResponse: (response: unknown) => Promise<boolean>; |
| 8 | +} |
| 9 | + |
| 10 | +// @note: returns already parsed response |
| 11 | +type SolidFetch = (input: string, init?: RequestInit) => Promise<unknown>; |
| 12 | + |
| 13 | +export function makeSolidFetch(opts: MakeSolidFetchOptions): SolidFetch { |
| 14 | + const solidFetch = fetchRetry(self.fetch, { |
| 15 | + retries: 3, |
| 16 | + async retryOn(_attempt, error, response) { |
| 17 | + const retry = error !== null || !response?.ok; |
| 18 | + if (retry) { |
| 19 | + // eslint-disable-next-line no-console |
| 20 | + console.log("Retrying failed fetch", { |
| 21 | + error, |
| 22 | + status: response?.status, |
| 23 | + }); |
| 24 | + } |
| 25 | + // if we have a response, we verify it and decide if we should retry |
| 26 | + if (!retry) { |
| 27 | + const responseJson = await response.clone().json(); |
| 28 | + const verified = await opts.verifyResponse(responseJson); |
| 29 | + if (!verified) { |
| 30 | + console.log("Response verification failed, retrying..."); |
| 31 | + } |
| 32 | + |
| 33 | + return !verified; |
| 34 | + } |
| 35 | + |
| 36 | + return true; |
| 37 | + }, |
| 38 | + retryDelay: function (attempt) { |
| 39 | + return Math.pow(2, attempt) * 1000; |
| 40 | + }, |
| 41 | + }); |
| 42 | + |
| 43 | + return (input: string, init?: RequestInit) => |
| 44 | + solidFetch(input, init).then((response) => response.json()); |
| 45 | +} |
0 commit comments