React Native Axios Refresh Token Implementation When Parallel Requests

19-04-2020
initAxios() {
    var thiz = this;

    Axios.defaults.baseURL = Constants.BASE_API_URL;
    Axios.defaults.headers.common["Authorization"] = "Bearer 123";
    Axios.defaults.headers.common["Accept"] = "application/json; charset=UTF-8";
    Axios.defaults.headers.common["Language"] = "TR";
    //Axios.defaults.headers.common["Host"] = "localhost:44335";//todo remove in production
    Axios.interceptors.request.use((request: any) => {
      console.log("Starting Request", request.baseURL + request.url + " Params: " + JSON.stringify(request.data));
      return request;
    });

    // for multiple requests
    let isRefreshing = false;
    // @ts-ignore
    let failedQueue = [];

    const processQueue = (error: any, token = null) => {
      // @ts-ignore
      failedQueue.forEach(prom => {
        if (error) {
          prom.reject(error);
        } else {
          prom.resolve(token);
        }
      });

      failedQueue = [];
    };

    Axios.interceptors.response.use(function (response) {

      // Do something with response data
      if (response.data != null && response.data.message != null
        && response.data.message != ""
        && (response.status == 200 || response.status == 201)) {
        Toast.show(response.data.message, {
          duration: Toast.durations.SHORT,
          position: Toast.positions.BOTTOM,
          shadow: true, animation: true,
          hideOnPress: true, delay: 0,
          backgroundColor: '#62b643',
          textColor: '#fff',
          opacity: 1
        });

      }

      return response;
    }, function (error) {

      const {config, response: {status}} = error;
      const originalRequest = config;

      if (error.response.status == 401 && !originalRequest._retry) {

        if (isRefreshing) {
          return new Promise(function (resolve, reject) {
            failedQueue.push({resolve, reject})
          }).then(token => {
            originalRequest.headers['Authorization'] = 'Bearer ' + token;
            return Axios(originalRequest);
          }).catch(err => {
            return Promise.reject(err);
          })
        }

        originalRequest._retry = true;
        isRefreshing = true;

        return new Promise(function (resolve, reject) {
          AccessTokenHelper.createAccessTokenFromRefreshToken((token: String) => {
            Axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
            originalRequest.headers['Authorization'] = 'Bearer ' + token;
            // @ts-ignore
            processQueue(null, token);
            resolve(Axios(originalRequest));
            isRefreshing = false
          }, (err: String) => {
            AlertHelper.showMessage('Hata', "Your session is expired. Please login again", () => {
              reject(err);
            }, "OK");
          });
        });
      } else if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        // console.log(error.response.data);
        // console.log(error.response.status);
        // console.log(error.response.headers);
        if (error.response.data != null && error.response.data.message != null)
          AlertHelper.show('Hata', error.response.data.message);

      } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        console.log(error.request);
      } else {
        // Something happened in setting up the request that triggered an Error

        console.log('Error', error.message);
      }
      console.log(error.config);

      return Promise.reject(error);
    });
  }

© 2019 All rights reserved. Codesenior.COM