source: frontend/node_modules/p-retry/index.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 2.0 KB
Line 
1'use strict';
2const retry = require('retry');
3
4const networkErrorMsgs = [
5 'Failed to fetch', // Chrome
6 'NetworkError when attempting to fetch resource.', // Firefox
7 'The Internet connection appears to be offline.', // Safari
8 'Network request failed' // `cross-fetch`
9];
10
11class AbortError extends Error {
12 constructor(message) {
13 super();
14
15 if (message instanceof Error) {
16 this.originalError = message;
17 ({message} = message);
18 } else {
19 this.originalError = new Error(message);
20 this.originalError.stack = this.stack;
21 }
22
23 this.name = 'AbortError';
24 this.message = message;
25 }
26}
27
28const decorateErrorWithCounts = (error, attemptNumber, options) => {
29 // Minus 1 from attemptNumber because the first attempt does not count as a retry
30 const retriesLeft = options.retries - (attemptNumber - 1);
31
32 error.attemptNumber = attemptNumber;
33 error.retriesLeft = retriesLeft;
34 return error;
35};
36
37const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage);
38
39const pRetry = (input, options) => new Promise((resolve, reject) => {
40 options = {
41 onFailedAttempt: () => {},
42 retries: 10,
43 ...options
44 };
45
46 const operation = retry.operation(options);
47
48 operation.attempt(async attemptNumber => {
49 try {
50 resolve(await input(attemptNumber));
51 } catch (error) {
52 if (!(error instanceof Error)) {
53 reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
54 return;
55 }
56
57 if (error instanceof AbortError) {
58 operation.stop();
59 reject(error.originalError);
60 } else if (error instanceof TypeError && !isNetworkError(error.message)) {
61 operation.stop();
62 reject(error);
63 } else {
64 decorateErrorWithCounts(error, attemptNumber, options);
65
66 try {
67 await options.onFailedAttempt(error);
68 } catch (error) {
69 reject(error);
70 return;
71 }
72
73 if (!operation.retry(error)) {
74 reject(operation.mainError());
75 }
76 }
77 }
78 });
79});
80
81module.exports = pRetry;
82// TODO: remove this in the next major version
83module.exports.default = pRetry;
84
85module.exports.AbortError = AbortError;
Note: See TracBrowser for help on using the repository browser.