All files / src/utils axiosInstance.ts

33.33% Statements 8/24
16.67% Branches 1/6
20% Functions 1/5
33.33% Lines 8/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49    5x     5x                           5x   10x   10x 10x 10x               5x                              
import axios from 'axios';
 
export const axiosInstance = axios.create();
 
//getting new tokens
const getNewTokens = async () => {
  try {
    const refreshToken = localStorage.getItem('refreshToken');
    const { data } = await axiosInstance.get(
      `${process.env.REACT_APP_API_URL}/token/refresh?refreshToken=${refreshToken}`,
    );
    localStorage.setItem('userToken', data.token);
    localStorage.setItem('refreshToken', data.refreshToken);
    return data.token;
  } catch (e) {
    console.log(e);
  }
};
 
axiosInstance.interceptors.request.use(
  (request) => {
    const token = localStorage.getItem('userToken');
 
    request.headers['Content-Type'] = 'application/json';
    request.headers['Authorization'] = token ? `Bearer ${token}` : '';
    return request;
  },
  (error) => {
    Promise.reject(error);
  },
);
 
// Response interceptor for API calls
axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    const originalRequest = error.config;
    if (error.response.status === 403 && !originalRequest._retry) {
      originalRequest._retry = true;
      const access_token = await getNewTokens();
      axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`;
      return axiosInstance(originalRequest);
    }
    return Promise.reject(error);
  },
);