Created
August 22, 2024 16:27
-
-
Save micaiah-effiong/6a4a8297d0017caf6fa9261c094329f9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { jwtDecode } from "jwt-decode"; | |
| import * as api from "./generated"; | |
| import { ApiRequestOptions } from "./generated/core/ApiRequestOptions"; | |
| import { toast } from "react-toastify"; | |
| import { storageKey } from "@/utils/keys"; | |
| api.OpenAPI.BASE = import.meta.env.VITE_APP_BASE_API; | |
| export const apiConfig = api; | |
| apiConfig.OpenAPI.TOKEN = async (_: ApiRequestOptions) => { | |
| const token = getTokenFromStore(storageKey.token); | |
| console.log("getting token", token); | |
| return token; | |
| }; | |
| export function getTokenFromStore(key: string) { | |
| const rawToken = localStorage.getItem(key) ?? "null"; | |
| const parsedToken = JSON.parse(rawToken) ?? null; | |
| if (parsedToken === null) { | |
| return parsedToken; | |
| } | |
| const decoded = jwtDecode(rawToken); | |
| const expireAt = (decoded.exp || 0) * 1000; | |
| if (expireAt < Date.now()) { | |
| localStorage.setItem(key, JSON.stringify(null)); | |
| localStorage.setItem(storageKey.user, JSON.stringify(null)); | |
| toast.error("Token expired", {}); | |
| window.location.replace("/login"); | |
| return null; | |
| } | |
| return parsedToken; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment