retry-axios

Retry HTTP requests with Axios.

retry-axios

Use Axios interceptors to automatically retry failed requests. Super flexible. Built in exponential backoff.

Installation

npm install retry-axios

Usage

To use this library, import it alongside of axios:

// Just import rax and your favorite version of axios
const rax = require('retry-axios');
const axios = require('axios');

Or, if you're using TypeScript / es modules:

import * as rax from 'retry-axios';
import axios from 'axios';

You can attach to the global axios object, and retry 3 times by default:

const interceptorId = rax.attach();
const res = await axios('https://test.local');

Or you can create your own axios instance to make scoped requests:

const myAxiosInstance = axios.create();
myAxiosInstance.defaults.raxConfig = {
  instance: myAxiosInstance
};
const interceptorId = rax.attach(myAxiosInstance);
const res = await myAxiosInstance.get('https://test.local');

You have a lot of options...

const interceptorId = rax.attach();
const res = await axios({
  url: 'https://test.local',
  raxConfig: {
    // Retry 3 times on requests that return a response (500, etc) before giving up.  Defaults to 3.
    retry: 3,

    // Retry twice on errors that don't return a response (ENOTFOUND, ETIMEDOUT, etc).
    noResponseRetries: 2,

    // Milliseconds to delay at first.  Defaults to 100.
    retryDelay: 100,

    // HTTP methods to automatically retry.  Defaults to:
    // ['GET', 'HEAD', 'OPTIONS', 'DELETE', 'PUT']
    httpMethodsToRetry: ['GET', 'HEAD', 'OPTIONS', 'DELETE', 'PUT'],

    // The response status codes to retry.  Supports a double
    // array with a list of ranges.  Defaults to:
    // [[100, 199], [429, 429], [500, 599]]
    statusCodesToRetry: [[100, 199], [429, 429], [500, 599]],

    // If you are using a non static instance of Axios you need
    // to pass that instance here (const ax = axios.create())
    instance: ax,

    // You can set the backoff type.
    // options are 'exponential' (default), 'static' or 'linear'
    backoffType: 'exponential',

    // You can detect when a retry is happening, and figure out how many
    // retry attempts have been made
    onRetryAttempt: err => {
      const cfg = rax.getConfig(err);
      console.log(`Retry attempt #${cfg.currentRetryAttempt}`);
    }
  }
});

If the logic in onRetryAttempt requires to be asynchronous, you can return a promise, then retry will be executed only after the promise is resolved:

const res = await axios({
  url: 'https://test.local',
  raxConfig: {
    onRetryAttempt: err => {
      return new Promise((resolve, reject) => {
        // call a custom asynchronous function
        refreshToken(err, function(token, error) {
          if (!error) {
            window.localStorage.setItem('token', token);
            resolve();
          } else {
            reject();
          }
        });
      });
    }
  }
});

Or if you want, you can just decide if it should retry or not:

const res = await axios({
  url: 'https://test.local',
  raxConfig: {
    // Override the decision making process on if you should retry
    shouldRetry: err => {
      const cfg = rax.getConfig(err);
      return true;
    }
  }
});

How it works

This library attaches an interceptor to an axios instance you pass to the API. This way you get to choose which version of axios you want to run, and you can compose many interceptors on the same request pipeline.

License

Apache-2.0

Repository

https://github.com/JustinBeckwith/retry-axios.git


上一篇:@percy/tslint
下一篇:percy-client

相关推荐

  • 使用ES7的 Decorator(修饰器)封装 axios

    retrofit-cjs 是一个基于JavaScript装饰器(Decorator)和 axios 实现的网络请求库, 支持Vue / React / react-native 等常用框架, 支持n...

    2 年前
  • superagent-retry

    A retrying layer for a superagent request superagent-retry Extends the node version of visionmedia...

    2 年前
  • socket-retry-connect

    Attempt to connect to socket multiple times Socket retry connect Tiny helper lib that will retry con...

    6 个月前
  • servicebus-retry

    retry middleware for servicebus servicebus-retry servicebus-retry adds message acknowledge, reject, ...

    5 个月前
  • retryme

    A more intuitive node-retry which behaves more like async.retry. Utilizes Backo under the hood for b...

    2 年前
  • retry-request

    Retry a request. Retry a request with built-in exponential backoff. $ npm install --save re...

    2 年前
  • retry-promise

    Small utility function that automatically retries Promises. retry-promise Small utility function to...

    6 个月前
  • retry-as-promised

    Retry a failed promise retry-as-promised Retry promises when they fail, based upon any-promise. Inst...

    2 年前
  • retry

    Abstraction for exponential and custom retry strategies for failed operations. retry Abstractio...

    2 年前
  • requestretry

    request-retry wrap nodejs request to retry http(s) requests in case of error request-retry - HTTP...

    2 年前

公众号

欢迎 JavaScript 爱好者