Created
December 7, 2021 14:57
-
-
Save marcelmokos/03f1f9ffa9ac10534f964fc6c1a0a088 to your computer and use it in GitHub Desktop.
Axios instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from "axios"; | |
import {history} from "../helpers/history"; | |
import { | |
makeAuthorizationHeader, | |
isTokenValid, | |
getToken, | |
setToken, | |
tokenIsExpired, | |
} from "../helpers/token"; | |
export const apiUrl = process.env.REACT_APP_API_URL; | |
const instance = axios.create({ | |
baseURL: apiUrl, | |
headers: { | |
Accept: "application/json", | |
}, | |
}); | |
instance.interceptors.request.use( | |
(config) => { | |
if (!config.baseURL) { | |
throw Error("Missing API base url"); | |
} | |
const {origin} = new URL(config.baseURL as string); | |
const allowedOrigins = [apiUrl]; | |
const token = getToken() as string; | |
if ( | |
allowedOrigins.includes(origin) && | |
isTokenValid(token) && | |
!tokenIsExpired(token) | |
) { | |
config.headers.authorization = makeAuthorizationHeader(token); | |
} | |
return config; | |
}, | |
(error) => { | |
return Promise.reject(error); | |
}, | |
); | |
instance.interceptors.response.use( | |
(response) => { | |
//response interceptor to refresh token on receiving token expired error | |
const refreshedToken = response.headers["x-refreshed-jwt"]; | |
if (refreshedToken) { | |
setToken({refreshedToken}); | |
} | |
return response; | |
}, | |
(error) => { | |
//response interceptor for status 409 - locked state require redirect to in-revision page | |
if (error.response.status === 409) { | |
history.push("/in-progress"); | |
return; | |
} | |
return Promise.reject(error); | |
}, | |
); | |
export default instance; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment