[6a3a178] | 1 | 'use strict';
|
---|
| 2 | const retry = require('retry');
|
---|
| 3 |
|
---|
| 4 | class 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 |
|
---|
| 21 | function 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 |
|
---|
| 31 | module.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 |
|
---|
| 60 | module.exports.AbortError = AbortError;
|
---|