Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Axios retry middleware for requests
import Axios from "axios";
import { LogService } from "../services/log-service";
import getAndRegisterGeneralToken, {
getGeneralToken,
removeGeneralToken,
} from "../services/token-service";
const instance = Axios.create();
instance.defaults.baseURL = "http://localhost:3000/graphql";
/*
* Request Interceptor
*/
instance.interceptors.request.use((config) => {
const generalToken = getGeneralToken();
if (generalToken) {
config.headers.Authorization = `Bearer ${generalToken}`;
}
return config;
});
const handleResponseError = async (error) => {
const statusCode = error?.response?.status;
if (statusCode === 401) {
removeGeneralToken();
await getAndRegisterGeneralToken();
if (error.response?.config) {
return getTokenForUnAuthorized(error);
}
} else {
LogService.log(error); // only log issues that are not related to expiry of token
}
return Promise.reject(error);
};
async function getTokenForUnAuthorized(error) {
const generalToken = getGeneralToken();
error.response.config.headers.Authorization = `Bearer ${generalToken}`;
const response = await Axios.request(error.response.config);
return response?.data ?? response;
}
instance.interceptors.response.use((response) => {
return response?.data ?? response;
}, handleResponseError);
export default instance;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment