• Stars
    star
    482
  • Rank 91,212 (Top 2 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created almost 7 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ¦– A super flexible interceptor for Axios that makes it easy to retry requests.

retry-axios

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

NPM Version GitHub Actions 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' is limited by the 'retry' value.
    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

More Repositories

1

linkinator

🐿 Scurry around your site and find all those broken links.
TypeScript
1,014
star
2

go-yelp

go-yelp is a #golang wrapper for the Yelp REST API. It lets you do all kinds of interesting things like searching for businesses, getting user comments and ratings, and handling common errors. The library is written Go.
Go
38
star
3

YelpSharp

YelpSharp is a .NET wrapper for the Yelp REST API. It lets you do all kinds of interesting things like searching for businesses, getting user comments and ratings, and handling common errors. The library is written in C#, and available on NuGet.
C#
38
star
4

gcx

An API and CLI for deploying Google Cloud Functions in Node.js.
TypeScript
34
star
5

cloudcats

CloudCats is an example of using node.js and various Google Cloud APIs and services to solve the greatest question of our time: do developers prefer dogs or cats.
JavaScript
33
star
6

trebuchet

The lost UI for App Engine.
JavaScript
32
star
7

fitbit-discord-bot

It's a bot! For Fitbit and Discord.
TypeScript
32
star
8

yes-https

Say yes to https with express and connect.
JavaScript
31
star
9

linkinator-action

A GitHub Action that checks your README and other markdown for 404s.
JavaScript
30
star
10

flem

Flem is a local emulator for the App Engine Flexible Environment.
TypeScript
22
star
11

OrangeBits

OrangeBits is a WebMatrix extension that automatically compiles LESS, SaSS, and CoffeeScript
C#
18
star
12

appengine-perl

An example of running perl on Google App Engine.
CSS
17
star
13

wazstagram

an experiment with Windows Azure and the Instagram Realtime API
JavaScript
12
star
14

awwbotcf

An example of a Discord Bot using Cloudflare Workers.
JavaScript
11
star
15

promotime

Fetch all those GitHub stats
JavaScript
10
star
16

TwitterMap

A happy little node.js app that posts tweets with geo location to a bing map.
JavaScript
9
star
17

hatspin

HatSpin: Connecting LittleBits and the cloud with node.js
JavaScript
9
star
18

npmtrace

Measure the load time of npm modules and their dependencies.
HTML
8
star
19

fileLister

JavaScript
7
star
20

linked-role-bot

An example of a Discord Bot for providing Linked Roles
JavaScript
7
star
21

next17

A collection of demos from GCP Next 17
JavaScript
6
star
22

gcbuild

πŸ‘·πŸΌβ€β™‚οΈπŸ›  A super simple CLI and API for using Google Cloud Build
TypeScript
6
star
23

frink

Frink is a reddit client designed for Tablets
JavaScript
6
star
24

SignalRMap

This is an example of using SignalR with Bing maps to provide a user map.
JavaScript
5
star
25

coffee

A silly Go / Gin app that finds coffee based on my current location.
Go
5
star
26

visionator

An example of using the Google Cloud Vision API to make a little magic.
JavaScript
5
star
27

node6-appengine

An example of running node.js v6 on Google App Engine
JavaScript
4
star
28

pollster

A node.js web application for polling the audience during a live talk.
CSS
4
star
29

Chogger-Bookmarklet

This code provides a jQuery based bookmarklet for directing images to chogger.com
JavaScript
4
star
30

WMV-Parser

Provides a framework for parsing data structures in a WMV / ASF container.
C#
3
star
31

revel-appengine

A simple example of running Revel Go applications with docker in Google App Engine.
HTML
3
star
32

cicd

A CI/CD story.
JavaScript
2
star
33

justinbeckwith.github.io

The Jekyll site I use for my blog.
HTML
2
star
34

gorgs

Scan GitHub issues within an organization. Stuff em in memory. Serve em up hot πŸ”₯
JavaScript
2
star
35

redditml

A few fun little programs that help us learn about the data on Reddit.
JavaScript
2
star
36

is-broke

TypeScript
1
star
37

bisquick

πŸ₯žSynchronize your GitHub issues with BigQuery. Do neat stuff.
C#
1
star
38

nsolid-docker

Just a few dockerfiles and guides for running nsolid in the cloud.
JavaScript
1
star
39

cloud-visionator

A little experiment with Ruby, Sinatra, and the Google Cloud Vision API
JavaScript
1
star
40

fileinator

Behold my latest inator! Generate files full of random bytes. That's about it.
JavaScript
1
star
41

wario

🎲 Wario is an opinionated tool for working against many git repositories at once.
Dart
1
star
42

flakybot-action

TypeScript
1
star
43

PhotoR

A simple demo of sharing pictures using ASP.NET, SignalR, and Windows Azure
JavaScript
1
star
44

DjangoFun

This is a playground for learning all about Django
Python
1
star
45

PhotoCloud

A demo ASP.NET Web Pages application built for for Channel 9.
JavaScript
1
star
46

pumpify

A fancy fork of mafintosh/pumpify. Combine an array of streams into a single duplex stream using pump and duplexify.
1
star
47

sloth-sheet-sync

This is a very silly application that just takes issues from sloth, and puts them in a sheet.
JavaScript
1
star
48

conference-proposals

A list of conference talk proposals I've submitted. πŸ—£πŸ—£πŸ—£
1
star
49

photobooth

A demo app used for GCP Next 17
JavaScript
1
star
50

gmail-notifier

A GitHub Action that sends emails via the Gmail API.
TypeScript
1
star
51

WebMatrixDocs

JavaScript
1
star
52

AppHarborDemo

This is a demo of using the PaaS components of AppHarbor.com
JavaScript
1
star
53

Templatizer

C#
1
star
54

waldo

waldo is... complicated.
Ruby
1
star
55

discord-js-auth

You probably don't want to be using this
TypeScript
1
star