|
1
|
import { setTimeout } from "timers/promises" |
|
2
|
|
|
3
|
export async function fetchAndRetry( |
|
4
|
func: () => Promise<any>, |
|
5
|
validation?: (data: any) => boolean, |
|
6
|
{ |
|
7
|
retries = 3, |
|
8
|
waitSeconds = 1, |
|
9
|
}: { |
|
10
|
retries?: number |
|
11
|
waitSeconds?: number |
|
12
|
} = {} |
|
13
|
) { |
|
14
|
while (retries >= 0) { |
|
15
|
try { |
|
16
|
const res = await func() |
|
17
|
|
|
18
|
if (validation && !validation(res)) { |
|
19
|
throw new Error("Validation failed. Retry...") |
|
20
|
} |
|
21
|
|
|
22
|
return res |
|
23
|
} catch (err) { |
|
24
|
if (retries > 0) { |
|
25
|
retries-- |
|
26
|
await setTimeout(waitSeconds * 1000) |
|
27
|
continue |
|
28
|
} |
|
29
|
throw err |
|
30
|
} |
|
31
|
} |
|
32
|
} |