index.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. var __importDefault = (this && this.__importDefault) || function (mod) {
  12. return (mod && mod.__esModule) ? mod : { "default": mod };
  13. };
  14. Object.defineProperty(exports, "__esModule", { value: true });
  15. exports.DEFAULT_OPTIONS = exports.exponentialDelay = exports.isNetworkOrIdempotentRequestError = exports.isIdempotentRequestError = exports.isSafeRequestError = exports.isRetryableError = exports.isNetworkError = exports.namespace = void 0;
  16. const is_retry_allowed_1 = __importDefault(require("is-retry-allowed"));
  17. exports.namespace = 'axios-retry';
  18. function isNetworkError(error) {
  19. const CODE_EXCLUDE_LIST = ['ERR_CANCELED', 'ECONNABORTED'];
  20. if (error.response) {
  21. return false;
  22. }
  23. if (!error.code) {
  24. return false;
  25. }
  26. // Prevents retrying timed out & cancelled requests
  27. if (CODE_EXCLUDE_LIST.includes(error.code)) {
  28. return false;
  29. }
  30. // Prevents retrying unsafe errors
  31. return (0, is_retry_allowed_1.default)(error);
  32. }
  33. exports.isNetworkError = isNetworkError;
  34. const SAFE_HTTP_METHODS = ['get', 'head', 'options'];
  35. const IDEMPOTENT_HTTP_METHODS = SAFE_HTTP_METHODS.concat(['put', 'delete']);
  36. function isRetryableError(error) {
  37. return (error.code !== 'ECONNABORTED' &&
  38. (!error.response || (error.response.status >= 500 && error.response.status <= 599)));
  39. }
  40. exports.isRetryableError = isRetryableError;
  41. function isSafeRequestError(error) {
  42. var _a;
  43. if (!((_a = error.config) === null || _a === void 0 ? void 0 : _a.method)) {
  44. // Cannot determine if the request can be retried
  45. return false;
  46. }
  47. return isRetryableError(error) && SAFE_HTTP_METHODS.indexOf(error.config.method) !== -1;
  48. }
  49. exports.isSafeRequestError = isSafeRequestError;
  50. function isIdempotentRequestError(error) {
  51. var _a;
  52. if (!((_a = error.config) === null || _a === void 0 ? void 0 : _a.method)) {
  53. // Cannot determine if the request can be retried
  54. return false;
  55. }
  56. return isRetryableError(error) && IDEMPOTENT_HTTP_METHODS.indexOf(error.config.method) !== -1;
  57. }
  58. exports.isIdempotentRequestError = isIdempotentRequestError;
  59. function isNetworkOrIdempotentRequestError(error) {
  60. return isNetworkError(error) || isIdempotentRequestError(error);
  61. }
  62. exports.isNetworkOrIdempotentRequestError = isNetworkOrIdempotentRequestError;
  63. function noDelay() {
  64. return 0;
  65. }
  66. function exponentialDelay(retryNumber = 0, _error = undefined, delayFactor = 100) {
  67. const delay = Math.pow(2, retryNumber) * delayFactor;
  68. const randomSum = delay * 0.2 * Math.random(); // 0-20% of the delay
  69. return delay + randomSum;
  70. }
  71. exports.exponentialDelay = exponentialDelay;
  72. exports.DEFAULT_OPTIONS = {
  73. retries: 3,
  74. retryCondition: isNetworkOrIdempotentRequestError,
  75. retryDelay: noDelay,
  76. shouldResetTimeout: false,
  77. onRetry: () => { },
  78. onMaxRetryTimesExceeded: () => { }
  79. };
  80. function getRequestOptions(config, defaultOptions) {
  81. return Object.assign(Object.assign(Object.assign({}, exports.DEFAULT_OPTIONS), defaultOptions), config[exports.namespace]);
  82. }
  83. function setCurrentState(config, defaultOptions) {
  84. const currentState = getRequestOptions(config, defaultOptions || {});
  85. currentState.retryCount = currentState.retryCount || 0;
  86. currentState.lastRequestTime = currentState.lastRequestTime || Date.now();
  87. config[exports.namespace] = currentState;
  88. return currentState;
  89. }
  90. function fixConfig(axiosInstance, config) {
  91. // @ts-ignore
  92. if (axiosInstance.defaults.agent === config.agent) {
  93. // @ts-ignore
  94. delete config.agent;
  95. }
  96. if (axiosInstance.defaults.httpAgent === config.httpAgent) {
  97. delete config.httpAgent;
  98. }
  99. if (axiosInstance.defaults.httpsAgent === config.httpsAgent) {
  100. delete config.httpsAgent;
  101. }
  102. }
  103. function shouldRetry(currentState, error) {
  104. return __awaiter(this, void 0, void 0, function* () {
  105. const { retries, retryCondition } = currentState;
  106. const shouldRetryOrPromise = (currentState.retryCount || 0) < retries && retryCondition(error);
  107. // This could be a promise
  108. if (typeof shouldRetryOrPromise === 'object') {
  109. try {
  110. const shouldRetryPromiseResult = yield shouldRetryOrPromise;
  111. // keep return true unless shouldRetryPromiseResult return false for compatibility
  112. return shouldRetryPromiseResult !== false;
  113. }
  114. catch (_err) {
  115. return false;
  116. }
  117. }
  118. return shouldRetryOrPromise;
  119. });
  120. }
  121. function handleMaxRetryTimesExceeded(currentState, error) {
  122. return __awaiter(this, void 0, void 0, function* () {
  123. if (currentState.retryCount >= currentState.retries)
  124. yield currentState.onMaxRetryTimesExceeded(error, currentState.retryCount);
  125. });
  126. }
  127. const axiosRetry = (axiosInstance, defaultOptions) => {
  128. const requestInterceptorId = axiosInstance.interceptors.request.use((config) => {
  129. setCurrentState(config, defaultOptions);
  130. return config;
  131. });
  132. const responseInterceptorId = axiosInstance.interceptors.response.use(null, (error) => __awaiter(void 0, void 0, void 0, function* () {
  133. const { config } = error;
  134. // If we have no information to retry the request
  135. if (!config) {
  136. return Promise.reject(error);
  137. }
  138. const currentState = setCurrentState(config, defaultOptions);
  139. if (yield shouldRetry(currentState, error)) {
  140. currentState.retryCount += 1;
  141. const { retryDelay, shouldResetTimeout, onRetry } = currentState;
  142. const delay = retryDelay(currentState.retryCount, error);
  143. // Axios fails merging this configuration to the default configuration because it has an issue
  144. // with circular structures: https://github.com/mzabriskie/axios/issues/370
  145. fixConfig(axiosInstance, config);
  146. if (!shouldResetTimeout && config.timeout && currentState.lastRequestTime) {
  147. const lastRequestDuration = Date.now() - currentState.lastRequestTime;
  148. const timeout = config.timeout - lastRequestDuration - delay;
  149. if (timeout <= 0) {
  150. return Promise.reject(error);
  151. }
  152. config.timeout = timeout;
  153. }
  154. config.transformRequest = [(data) => data];
  155. yield onRetry(currentState.retryCount, error, config);
  156. return new Promise((resolve) => {
  157. setTimeout(() => resolve(axiosInstance(config)), delay);
  158. });
  159. }
  160. yield handleMaxRetryTimesExceeded(currentState, error);
  161. return Promise.reject(error);
  162. }));
  163. return { requestInterceptorId, responseInterceptorId };
  164. };
  165. // Compatibility with CommonJS
  166. axiosRetry.isNetworkError = isNetworkError;
  167. axiosRetry.isSafeRequestError = isSafeRequestError;
  168. axiosRetry.isIdempotentRequestError = isIdempotentRequestError;
  169. axiosRetry.isNetworkOrIdempotentRequestError = isNetworkOrIdempotentRequestError;
  170. axiosRetry.exponentialDelay = exponentialDelay;
  171. axiosRetry.isRetryableError = isRetryableError;
  172. exports.default = axiosRetry;