Skip to content

Commit

Permalink
Optimize refresh token for dispatch actions (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
quietbits authored Oct 30, 2023
1 parent 8ec2a42 commit 168cecf
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions src/api/refreshToken.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,32 @@
import { API_URL } from "constants/settings";
import { differenceInMinutes, fromUnixTime } from "date-fns";
import { API_URL, SESSION_EXPIRED } from "constants/settings";
import { parseJwt } from "helpers/parseJwt";

export const refreshToken = async (token: string): Promise<string> => {
const response = await fetch(`${API_URL}/refresh-token`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
const jwt = parseJwt(token);
// JWT session is 15 min
const minRemaining = differenceInMinutes(fromUnixTime(jwt.exp), Date.now());

const responseJson = await response.json();
if (minRemaining <= 0) {
throw SESSION_EXPIRED;
} else if (minRemaining < 5) {
const response = await fetch(`${API_URL}/refresh-token`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});

if (responseJson.token) {
return responseJson.token;
const responseJson = await response.json();

if (responseJson.token) {
return responseJson.token;
}

throw responseJson;
}

throw responseJson;
// Return current token
return token;
};

0 comments on commit 168cecf

Please sign in to comment.