banner

KuchBhiLearning - A free website to learn and code

This is a good learning site. This contains details of cloud computing, AWS, AWS-CDK, AWS-SDK codes and examples including S3, Redis, lambda, api-gateway, cloudfront, cloudformation.

Retry Axios    

If you have been coding in javascript for a while, you'd probably have known about Axios. It is a famous JS library for making HTTP request. Whether you are back-end or front-end developer, Axios is essential to access API services.

In this post, I'm going to show how to equip Axios with retry capability i.e resend HTTP request when server doesn't answer.


Retry-Axios second most popular retry add-on for Axios.


Install using the below command


npm install retry-axios


Below is the working code


const rax = require('retry-axios');
const axios = require('axios');

rax.attach();
const myRequest = async () => {
  try {
    const myConfig = {
      raxConfig: {
        retry: 5, // number of retry when facing 4xx or 5xx
        noResponseRetries: 5, // number of retry when facing connection error
        onRetryAttempt: err => {
          const cfg = rax.getConfig(err);
          console.log(`Retry attempt #${cfg.currentRetryAttempt}`); // track current trial
        }
      },
      timeout: 50 // don't forget this one
    }
    const req = await axios.get('https://mock.codes/200', myConfig);
    console.log(req.data);
  } catch (error) {
    console.log(error);
  }
}

myRequest();

I basically attached retry-axios object to Axios. My part is handling config for the request.

That's it! Now we can make Axios more reliable in sending HTTP request. We can have multiple configuration, below is an example


const raxConfig = {
  // Retry 3 times on requests that return a response (500, etc) before giving up.  Defaults to 3.
  retry: 2,

  // 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,

  //   instance: myAxiosInstance,

  // 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],
    [400, 401],
  ],

  // You can detect when a retry is happening, and figure out how many
  // retry attempts have been made
  onRetryAttempt: (err: any) => {
    const cfg = rax.getConfig(err) || {};
    console.log(`Retry attempt #${cfg.currentRetryAttempt}`);
  },
  shouldRetry: (err: any) => {
    const cfg = rax.getConfig(err) || {};
    console.log('should retry', err);
    if ((cfg.currentRetryAttempt || 0) >= (cfg.retry || 1)) return false; // ensure max retries is always respected

    if (err.response.status === 400) return true;
    return rax.shouldRetryRequest(err);
  },
};

Hope this helps.




No comments:

Post a Comment

If you have any doubts, Please let me know

Copyright 2022, KuchBhiLearning - A free website to learn and code. All rights Reserved.
| Designed by Yaseen Shariff