-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (47 loc) · 1.44 KB
/
index.js
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict'
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
module.exports = async (url, opts) => {
let retry = opts && opts.retry || 3
const initialRetry = retry
const accepted = opts && opts.accepted || [200]
const factor = opts && opts.factor || 1
let pause = opts && opts.pause || 1000
const verbose = opts && opts.verbose
/*
if(retry<=0)
{
const response = await fetch(url, opts)
return response;
}
*/
while (retry >= 0) {
try {
const responseRetry = await fetch(url, opts)
if(accepted.indexOf(responseRetry.status) > -1)
{
return responseRetry
}
var err = new Error('Status not accepted')
err.status = responseRetry.status
err.statusText = responseRetry.statusText
throw err
} catch(e) {
if (retry === 0) {
throw e
}
retry = retry - 1
if (opts && opts.callback) {
opts.callback(initialRetry-retry, e)
}
if (pause >= 0) {
if (verbose) console.log("pausing..");
await sleep(pause);
if (verbose) console.log("done pausing...");
}
pause = pause * factor
}
}
};
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}