Introduction to the

Axios’s interceptor is a nice design that allows us to do a lot of things and save on duplicate code.

Today’s focus is not on Axios, but on implementing an interceptor that pops up a friendly message when the network is slow. Similar to the following.

You can come here to experience: ngzhixiao gitee. IO/heiibaiitoy…

If you are on a computer, you can open the network on the console and choose slow 3G for a more realistic experience

implementation

// Records the id of the current request issued but not returned
    const requestMap = new Set(a)function generateId(url) {
      return url+new Date().getTime()+Math.random()
    }

    /** * Slow network alert interceptor, in the case of slow network alert user wait */
    const slowNetworkInterceptor = function(axios, slowTime = 5000) {

      if(! axios.defaults.headers.common.__config){ axios.defaults.headers.common.__config = {} } axios.defaults.headers.common.__config.slowNetworkConfig = { slowTime,// Define the network slow condition
        close: false.// Allows the prompt to be turned off on some interfaces
      }

      axios.interceptors.request.use(config= > {
        const snc = config.headers.common.__config.slowNetworkConfig
        if(snc.close) return config
        const id = generateId(config.url)
        requestMap.add(id)
        snc.id = id
        setTimeout(() = > {
          if(requestMap.has(id)) {
            Toast("The network seems to be deserting itself, please be patient.")
            requestMap.delete(id)
          }
        }, snc.slowTime);
        return config
      }, err= > Promise.reject(err))

      axios.interceptors.response.use(res= > {
        const snc = res.config.headers.__config.slowNetworkConfig
        if(snc.close) return res
        requestMap.delete(snc.id)
        return res
      }, err= > {
        const snc = err.config.headers.__config.slowNetworkConfig
        if(snc.close) return Promise.reject(err)
        requestMap.delete(snc.id)
        return Promise.reject(err)
      })

      return axios
    }

    slowNetworkInterceptor(axios)
Copy the code

The code is shown above.

An ID is generated on each request and stored in the request configuration config to mark the request. In the beginning we defined a requestMap to record the id of the network request that was made but not returned. Then start a timer (we give it 5s by default), and if the request returns within 5s, remove the corresponding ID from the returned interceptor. If it does not return within 5 seconds, we will prompt the user that the current network is slow.

One detail is why the ID and timer length information is not placed directly on the request object’s config but on headers. Put it on headers soon after with the request?

Before the request is made, Axios will merge the parameters in config, but only the parameters it defines, so if you put headers directly on config it will be excluded, while headers will do a deep copy with common up one level. This also explains why parameters set in Common in request interception can be retrieved directly from HEADERS in return interception.

This results in an extra parameter in the request header like __config: [object object], but in most cases this doesn’t matter.

conclusion

This is just one of the uses of interceptor. In fact, in the actual development process, we can also achieve the request signature, request data encryption and decryption, and even achieve the cache of the request cache and other operations.

Axios is a very cleverly designed library, and its code is very short. It is a good example of a good open source library, and I recommend checking out its source whenever you have time.

Finally hit an advertisement, we can pay attention to my public number: the front slowly learn. I will share some interesting content on it from time to time.