source: trip-planner-front/node_modules/p-retry/index.js@ 76712b2

Last change on this file since 76712b2 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.5 KB
Line 
1'use strict';
2const retry = require('retry');
3
4class AbortError extends Error {
5 constructor(message) {
6 super();
7
8 if (message instanceof Error) {
9 this.originalError = message;
10 ({message} = message);
11 } else {
12 this.originalError = new Error(message);
13 this.originalError.stack = this.stack;
14 }
15
16 this.name = 'AbortError';
17 this.message = message;
18 }
19}
20
21function decorateErrorWithCounts(error, attemptNumber, options) {
22 // Minus 1 from attemptNumber because the first attempt does not count as a retry
23 const retriesLeft = options.retries - (attemptNumber - 1);
24
25 error.attemptNumber = attemptNumber;
26 error.retriesLeft = retriesLeft;
27
28 return error;
29}
30
31module.exports = (input, options) => new Promise((resolve, reject) => {
32 options = Object.assign({
33 onFailedAttempt: () => {},
34 retries: 10
35 }, options);
36
37 const operation = retry.operation(options);
38
39 operation.attempt(attemptNumber => Promise.resolve(attemptNumber)
40 .then(input)
41 .then(resolve, error => {
42 if (error instanceof AbortError) {
43 operation.stop();
44 reject(error.originalError);
45 } else if (error instanceof TypeError) {
46 operation.stop();
47 reject(error);
48 } else if (operation.retry(error)) {
49 decorateErrorWithCounts(error, attemptNumber, options);
50 options.onFailedAttempt(error);
51 } else {
52 decorateErrorWithCounts(error, attemptNumber, options);
53 options.onFailedAttempt(error);
54 reject(operation.mainError());
55 }
56 })
57 );
58});
59
60module.exports.AbortError = AbortError;
Note: See TracBrowser for help on using the repository browser.