This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

Axios extension

In the last article, we talked about axios’ cache add-on. Today, we will talk about the other two Axios add-on – throttling add-on and retry add-on.

Note: Axios’s extensions are for GET requests

Axios installation

npm i axios -S // yarn add axios -s
Copy the code

Plug-in installation

NPM I axios-extensions -s // or YARN add axios-extensions -sCopy the code

Throttling plug-in

The cache plugin can be used if multiple requests are made at a certain time interval and data does not change frequently, but throttling plugin can be used if data is likely to change over a short period of time or if it is uncertain whether the data will change. Because its default interval is shorter than that of the cache plug-in, the default is 1s

The request will only be sent once in 1s. No other request is made, but the result of that request is returned.

use

throttleAdapterEnhancer(adapter, options)

Option object, optional

  • threshold

    The interval for throttling, of type Number, is 1000 milliseconds by default.

  • cache

    The Max (maximum number of throttling requests) can be configured, which defaults to 100 and can be overridden by the Cache object, as shown below

      import { Cache } from 'axios-extensions'
      const cache = new Cache({
       max: 100
      });
      throttleAdapterEnhancer(axios.defaults.adapter, {
       cache
      })
    Copy the code

It is recommended to use throttling plug-in and cache plug-in together

As follows:

throttleAdapterEnhancer(cacheAdapterEnhancer(axios.defaults.adapter, option), option)

Example:

import axios from 'axios';
import { throttleAdapterEnhancer } from 'axios-extensions';

const instance = axios.create({
	adapter: throttleAdapterEnhancer(axios.defaults.adapter)
});

instance.get('/test'); // Make a request
instance.get('/test'); // Cache requests

setTimeout(() = > {
  instance.get('/test'); // Make a request
}, 2000)

Copy the code

Retry the plugin

If our request fails, Axios defaults to abort and does not help us re-initiate the request. The axios retry plug-in can now add a retry mechanism.

use

retryAdapterEnhancer(adapter, options)

Option object, optional

  • times

    Number Number of retries. The default value is 2. The request will be retried twice if it fails.

import axios from 'axios';
import { retryAdapterEnhancer } from 'axios-extensions';

const instance = axios.create({
    adapter: retryAdapterEnhancer(axios.defaults.adapter,{times: 3})});// If the request fails, it will be retried three times
instance.get('/users')

// The request is rewritten for five times. If the request fails, five retries are performed
instance.get('/special', { retryTimes: 5 });

Copy the code