Skip to content

Commit

Permalink
added refreshing the expired acces token functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
TharindaPrabhath committed Oct 1, 2021
1 parent 42fcac5 commit 8355063
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions src/utils/axios.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import axios from "axios";
import requests from "../data/requests";
import useLocalStorage from "./useLocalStorage";
import useTokenService from "./useTokenService";

// export const API_BASE_URL = "http://localhost:8080/api/v1";
//export const API_BASE_URL = "http://localhost:8080/api/v1";
export const API_BASE_URL = "https://symetry-certify.herokuapp.com/api/v1"
const useAxios = () => {
const { getAccessToken } = useTokenService();
const { setAccessToken, setAccessTokenExpiresAt,
getAccessToken, getRefreshToken,
getAccessTokenExpiresAt } = useTokenService();
const { getAdmin } = useLocalStorage();
const axiosInstance = axios.create(
{
headers: {
Expand All @@ -16,18 +21,27 @@ const useAxios = () => {
}
);

// axiosInstance.interceptors.response.use(
// (res)=>
// new Promise((resolve, reject)=>{
// resolve(res);
// }),
// (err)=>{
// if(err.response.status === 403){
// window.location.pathname = "/signin";
// }

// }
// )
axiosInstance.interceptors.request.use(async (config) => {
const expireAt = getAccessTokenExpiresAt();
if (Date.now() > Date.parse(expireAt!)) {
// access token has expired
// refreshing the access token
await axios.post(API_BASE_URL+requests.refreshToken, {
refreshToken: getRefreshToken(),
accessToken: getAccessToken(),
adminId: getAdmin().id,
}).then((res) => {
// setting updated token
setAccessToken(res.data.accessToken)
setAccessTokenExpiresAt(res.data.accessTokenExpiresAt)
}).catch((err)=> console.error(err))

}
return config;
}, (err) => {
console.error("error in getting ",err)
});

return axiosInstance;

}
Expand Down

0 comments on commit 8355063

Please sign in to comment.