Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run response interceptor only once when multiple API calls

I have an interceptor like this

axios.interceptors.response.use(undefined, err=> {
    const error = err.response;
    console.log(error);
    if (error.status===401 && error.config && !error.config.__isRetryRequest) {
        return axios.post(Config.oauthUrl + '/token', 'grant_type=refresh_token&refresh_token='+refreshToken,
            { headers: {
          'Authorization': 'Basic ' + btoa(Config.clientId + ':' + Config.clientSecret),
          'Content-Type': 'application/x-www-form-urlencoded,charset=UTF-8'
         }
       })
        .then(response => {
          saveTokens(response.data)
          error.config.__isRetryRequest = true;
          return axios(error.config)
        })
      } 
  })

And everything is working, but if I have like in my case 4 API calls on one React Component, and this error happens the same code will be run 4 times, meaning 4 times I will send my refresh token and get the auth token, and I would want to run it only once obviously

like image 685
high incompetance Avatar asked Sep 15 '16 10:09

high incompetance


People also ask

What are API interceptors?

Interceptor is an API gateway server built for accepting API requests from the client applications and routing them to the appropriate backend services. May it be a single service or multiple services to be called in a single API call, interceptor provides you with the necessary tools to control your API request flow.

What is Axios interceptors response use?

Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received. Interceptors are methods which are triggered before or after the main method.


1 Answers

I think you can queue authentication requests with something like:

let authTokenRequest;

// This function makes a call to get the auth token
// or it returns the same promise as an in-progress call to get the auth token
function getAuthToken() {
  if (!authTokenRequest) {
    authTokenRequest = makeActualAuthenticationRequest();
    authTokenRequest.then(resetAuthTokenRequest, resetAuthTokenRequest);
  }

  return authTokenRequest;
}

function resetAuthTokenRequest() {
  authTokenRequest = null;
}

And then in your interceptor...

axios.interceptors.response.use(undefined, err => {
  const error = err.response;
  if (error.status===401 && error.config && !error.config.__isRetryRequest) {
    return getAuthToken().then(response => {
      saveTokens(response.data);
      error.config.__isRetryRequest = true;
      return axios(error.config);
   });
  } 
});

I hope this helps you ;)

like image 147
Rubén Norte Avatar answered Sep 17 '22 10:09

Rubén Norte