Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Promise 상태로 분기처리하여 재요청 차단 #455

Merged
merged 1 commit into from
Sep 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions frontend/src/apis/getApi.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const abortController = new AbortController();
let refreshResponse: Promise<Response> | null = null;

const decodeToken = (token: string) => {
const tokenParts = token.split('.');
Expand All @@ -11,33 +11,37 @@ const decodeToken = (token: string) => {
return JSON.parse(decodedPayloadString);
};

async function refreshToken(headers: Headers): Promise<string> {
async function refreshToken(headers: Headers): Promise<Response> {
if (refreshResponse !== null) {
return refreshResponse;
}

const accessToken = localStorage.getItem('userToken');
try {
// 서버에 새로운 엑세스 토큰을 요청하기 위한 네트워크 요청을 보냅니다.
const refreshResponse = await fetch(`${DEFAULT_PROD_URL}/refresh-token`, {
refreshResponse = fetch(`${DEFAULT_PROD_URL}/refresh-token`, {
method: 'POST',
headers,
body: JSON.stringify({
accessToken: accessToken,
}),
signal: abortController.signal,
});

const responseData = await refreshResponse;
refreshResponse = null;

// 서버 응답이 성공적인지 확인합니다.
if (!refreshResponse.ok) {
if (!responseData.ok) {
console.log('refreshResponse.ok하지 못함');
throw new Error('Failed to refresh access token.');
}

// 새로운 엑세스 토큰을 반환합니다.
const responseBody = await refreshResponse.json();
return responseBody.accessToken;
return responseData;
} catch (error) {
// 네트워크 요청 실패 또는 예외 발생 시 예외를 캐치하여 처리합니다.
console.error('네트워크 요청 실패 또는 예외 발생:', error);
// throw error; // 예외를 다시 throw하여 상위 코드로 전파합니다.
return 'abort';
throw error; // 예외를 다시 throw하여 상위 코드로 전파합니다.
}
}

Expand All @@ -47,13 +51,9 @@ const isTokenExpired = (token: string) => {
};

async function updateToken(headers: Headers) {
const newToken = await refreshToken(headers);
if (newToken === 'abort') {
return;
}

localStorage.setItem('userToken', newToken);
abortController.abort();
const response = await refreshToken(headers);
const newToken = await response.json();
localStorage.setItem('userToken', newToken.accessToken);
}

async function withTokenRefresh<T>(callback: () => Promise<T>): Promise<T> {
Expand Down