Skip to content
Snippets Groups Projects
Api.ts 901 B
Newer Older
import axios from 'axios';
import { AxiosError, AxiosRequestConfig } from 'axios';
import { AuthoriseUser } from '../services/Authorise/Authorise';
  baseURL: 'http://localhost:5267/api/'
});
lcross2002's avatar
lcross2002 committed
const isAlreadyAuthUrl = (error: AxiosError) => {
  const full = error.request.responseURL as string;
  return full.endsWith('User/authorize');
};

Api.interceptors.response.use(
  (response) => response, // Normal success logic
  (error: AxiosError) => {
lcross2002's avatar
lcross2002 committed
    if (error.request.status === 401 && !isAlreadyAuthUrl(error)) { // If 401 (Unauthorized)
      AuthoriseUser().then((response: any) => { // Re-auth
        if (!response) // If no response then just return
          return;

        return Api.request(error.config as AxiosRequestConfig); // Redo the request
      });
    } else {
      throw error; // Otherwise throw error as normal
    }
  }
);

export default Api;