File size: 775 Bytes
109dd1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const sleep = async (delay) =>
  await new Promise((resolve) => setTimeout(resolve, delay));

export const fetchAndRetry = async (
  url,
  options,
  { fetchAfterMs = 200, retriesAfterMs = [200, 5 * 1000, 60 * 1000] } = {}
) => {
  let error;
  for (let retryAfterMs of retriesAfterMs) {
    try {
      await sleep(fetchAfterMs);
      const response = await fetch(url, options);
      if (!response.ok) {
        console.log(
          `Failed to fetch ${url}: ${response.status} ${
            response.statusText
          } - Headers: ${JSON.stringify(response.headers)}`
        );
        await sleep(response.headers.get("Retry-After") ?? retryAfterMs);
        continue;
      }
      return response;
    } catch (e) {
      error = e;
    }
  }
  throw error;
};