All Projects → JustinBeckwith → Retry Axios

JustinBeckwith / Retry Axios

Licence: apache-2.0
🦖 A super flexible interceptor for Axios that makes it easy to retry requests.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Retry Axios

guwen-react
guwennet.com 古文网 前端代码 古文 诗词 React + redux
Stars: ✭ 23 (-92.23%)
Mutual labels:  axios
Nuxt Blog
基于Nuxt.js服务器渲染(SSR)搭建的个人博客系统
Stars: ✭ 277 (-6.42%)
Mutual labels:  axios
Vue Zhihu Daily
🤓使用vue编写的练手的知乎日报WebApp(iOS版)
Stars: ✭ 285 (-3.72%)
Mutual labels:  axios
Vue Home
🏠 A simple project(Vue Community SPA) which bases on vue+vue-cli+vue-router+axios+ scss.
Stars: ✭ 256 (-13.51%)
Mutual labels:  axios
Tenacity
Retrying library for Python
Stars: ✭ 3,472 (+1072.97%)
Mutual labels:  retry
Vue Admin Design
基于vue + elementUI的管理系统模板
Stars: ✭ 279 (-5.74%)
Mutual labels:  axios
axios-for-observable
A RxJS wrapper for axios, same api as axios absolutely
Stars: ✭ 13 (-95.61%)
Mutual labels:  axios
Vue Testing Examples
Advanced testing with vuejs. When you need to go beyond Getting started section and see some real world example with everything that proper tests should have.
Stars: ✭ 288 (-2.7%)
Mutual labels:  axios
Vue Koa2 Login
基于 token 的登录注册。
Stars: ✭ 275 (-7.09%)
Mutual labels:  axios
Shkjem
基于Vue&ElementUI的企业官网
Stars: ✭ 281 (-5.07%)
Mutual labels:  axios
Column
Vue3.0+Typescript+axios+bootstrap+源码注释/博客专栏作品
Stars: ✭ 261 (-11.82%)
Mutual labels:  axios
Thwack
A tiny modern data fetching solution
Stars: ✭ 268 (-9.46%)
Mutual labels:  axios
Flutter advanced networkimage
flutter advanced network image provider
Stars: ✭ 282 (-4.73%)
Mutual labels:  retry
GLaDOS-CheckIn
GLaDOS AutoCheckIn 定时自动签到
Stars: ✭ 81 (-72.64%)
Mutual labels:  axios
Iview Admin
Vue 2.0 admin management system template based on iView
Stars: ✭ 15,963 (+5292.91%)
Mutual labels:  axios
react-movies-finder
React Movies finder is a React app to search movies and series using redux, redux-thunk, React Hooks, and Material UI
Stars: ✭ 27 (-90.88%)
Mutual labels:  axios
Dva Admin
dva admin antd dashboard
Stars: ✭ 278 (-6.08%)
Mutual labels:  axios
Restyped
End-to-end typing for REST APIs with TypeScript
Stars: ✭ 287 (-3.04%)
Mutual labels:  axios
Express React Fullstack
Simple, Useful Full Stack Express and React Application
Stars: ✭ 286 (-3.38%)
Mutual labels:  axios
Vue Scscms
基于koa2+mysql+vue2.0+Element阳光内容管理系统,模范学习Demo
Stars: ✭ 284 (-4.05%)
Mutual labels:  axios

retry-axios

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

NPM Version GitHub Actions Dependency Status Known Vulnerabilities codecov style badge

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. Only considered when backoffType is 'static'
    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;
    }
  }
});

If you want to add custom retry logic without duplicating too much of the built-in logic, rax.shouldRetryRequest will tell you if a request would normally be retried:

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);
      if (cfg.currentRetryAttempt >= cfg.retry) return false // ensure max retries is always respected

      // Always retry this status text, regardless of code or request type
      if (err.response.statusText.includes('Try again')) return true

      // Handle the request based on your other config options, e.g. `statusCodesToRetry`
      return rax.shouldRetryRequest(err)
    }
  }
});

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

David

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].