Access Token 저장 방식 변경

This commit is contained in:
static
2024-12-28 16:54:46 +09:00
parent 1d0c309878
commit c09a0b4aa0
10 changed files with 44 additions and 83 deletions

View File

@@ -1,48 +1,15 @@
import { get } from "svelte/store";
import { accessTokenStore } from "$lib/stores";
const refreshToken = async () => {
const res = await fetch("/api/auth/refreshToken", {
method: "POST",
credentials: "same-origin",
});
if (!res.ok) {
accessTokenStore.set(null);
throw new Error("Failed to refresh token");
}
const data = await res.json();
const token = data.accessToken as string;
accessTokenStore.set(token);
return token;
};
const callAPIInternal = async (
input: RequestInfo,
init: RequestInit | undefined,
token: string | null,
retryIfUnauthorized = true,
): Promise<Response> => {
if (!token) {
token = await refreshToken();
retryIfUnauthorized = false;
}
const res = await fetch(input, {
...init,
headers: {
...init?.headers,
Authorization: `Bearer ${token}`,
},
});
if (res.status === 401 && retryIfUnauthorized) {
return await callAPIInternal(input, init, null, false);
}
return res;
return await fetch("/api/auth/refreshToken", { method: "POST" });
};
export const callAPI = async (input: RequestInfo, init?: RequestInit) => {
return await callAPIInternal(input, init, get(accessTokenStore));
let res = await fetch(input, init);
if (res.status === 401) {
res = await refreshToken();
if (!res.ok) {
return res;
}
res = await fetch(input, init);
}
return res;
};