Skip to content

Instantly share code, notes, and snippets.

@shoaibmehedi7
Created March 25, 2022 09:06
Show Gist options
  • Save shoaibmehedi7/19bfd09b8efda9c21c58d5af4ff4d200 to your computer and use it in GitHub Desktop.
Save shoaibmehedi7/19bfd09b8efda9c21c58d5af4ff4d200 to your computer and use it in GitHub Desktop.
import axios from "axios";
import { baseUrl } from "../contants/Endpoints";
import jwt_decode from "jwt-decode";
import { noAuthAxios } from './axiosWrapperOpen';
import { asyncLocalStorage } from "./asyncLocalStorage";
export const authAxios = axios.create({
baseURL: baseUrl,
headers: {
Authorization: {
toString() {
const token = localStorage.getItem("jwt");
const decidedToken = isTokenExpired(token);
console.log("decidedToken", decidedToken);
return `Bearer ${decidedToken}`;
},
},
Accept: "application/json",
"Content-Type": "application/json",
},
});
function isTokenExpired(token){
try {
const decoded = jwt_decode(token);
if (decoded.exp < Date.now()/1000) {
return noAuthAxios.post(`${baseUrl}open/refresh_token`, {
refreshToken: localStorage.getItem("refreshToken"),
})
.then(async function (res) {
asyncLocalStorage.setItem("jwt", res.data.accessToken);
asyncLocalStorage.setItem("refreshToken", res.data.refreshToken);
return 'token';
});
} else {
console.log('token',"token not expired");
return token;
};
} catch (err) {
console.log(err, "err");
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment