-
Notifications
You must be signed in to change notification settings - Fork 0
[♻️ Refactor/123] 공통 및 비인증 API fetcher 구현 #126
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d8d1e5f
♻️ Refactor: coreFetch.ts 구현
chldntjr1321 3198ad6
♻️ Refactor: publicFetch.ts 구현
chldntjr1321 9a99637
♻️ Refactor: publicFetch 적용
chldntjr1321 585bc5d
Merge branch 'dev' into refactor/123/coreFetch
chldntjr1321 e2451d0
📝 Docs: publicFetch.ts TSDoc 추가
chldntjr1321 5cc3886
🐛 Fix: auth.ts publicFetch 적용
chldntjr1321 c377c15
♻️ Refactor: errorGuard.ts 적용
chldntjr1321 d4274b9
♻️ Refactor: isAbortError를 타입 가드 형태로 변경
chldntjr1321 1d6af4e
🔥 Remove: 로그인 API bffFetch 사용을 위한 주석처리
chldntjr1321 9786efb
Merge branch 'dev' into refactor/123/coreFetch
chldntjr1321 965238a
♻️ Refactor: abort 원인 구분 로직 추가
chldntjr1321 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import { isRecord } from '@/shared/utils/errorGuards'; | ||
|
|
||
| type ApiError = Error & { | ||
| status: number; | ||
| code?: string; | ||
| }; | ||
|
|
||
| type AbortError = { | ||
| name: 'AbortError'; | ||
| }; | ||
|
|
||
| export const isAbortError = (error: unknown): error is AbortError => { | ||
| if (!isRecord(error)) { | ||
| return false; | ||
| } | ||
|
|
||
| return error.name === 'AbortError'; | ||
| }; | ||
|
|
||
| /** | ||
| * ### coreFetch | ||
| * | ||
| * @description | ||
| * URL과 RequestInit 옵션을 받아 fetch 요청을 실행하는 공통 실행기 함수입니다. | ||
| * | ||
| * @error | ||
| * - 요청이 abort된 경우(시간 초과 또는 외부 취소), Error를 throw 합니다. | ||
| * - HTTP 상태 코드가 2xx가 아닌 경우, status와 code를 포함한 ApiError를 throw 합니다. | ||
| * | ||
| * @param url | ||
| * - 완성된 요청 URL | ||
| * @param options | ||
| * - fetch에 전달할 RequestInit 옵션 | ||
| * @param timeoutMs | ||
| * - 요청 제한 시간(ms), 기본값은 10초 | ||
| * | ||
| * @returns | ||
| * 응답이 204(No Content)인 경우 undefined를 반환하고 그 외는 JSON 파싱 데이터 반환 | ||
| */ | ||
| export const coreFetch = async <T>( | ||
| url: string, | ||
| options: RequestInit = {}, | ||
| timeoutMs: number = 10_000 | ||
| ): Promise<T> => { | ||
| const isFormData = typeof FormData !== 'undefined' && options.body instanceof FormData; | ||
|
|
||
| const request = async (): Promise<Response> => { | ||
| const controller = new AbortController(); | ||
| const headers = new Headers(options.headers); | ||
| let abortedByTimeout = false; | ||
|
|
||
| if (isFormData) { | ||
| headers.delete('Content-Type'); | ||
| } else if (!headers.has('Content-Type')) { | ||
| headers.set('Content-Type', 'application/json'); | ||
| } | ||
|
|
||
| let abortHandler: (() => void) | undefined; | ||
|
|
||
| if (options.signal) { | ||
| abortHandler = () => controller.abort(); | ||
|
|
||
| if (options.signal.aborted) { | ||
| controller.abort(); | ||
| } else { | ||
| options.signal.addEventListener('abort', abortHandler); | ||
| } | ||
| } | ||
|
|
||
| const timeoutId = setTimeout(() => { | ||
| abortedByTimeout = true; | ||
| controller.abort(); | ||
| }, timeoutMs); | ||
|
|
||
| try { | ||
| const response = await fetch(url, { | ||
| ...options, | ||
| signal: controller.signal, | ||
| headers, | ||
| }); | ||
| return response; | ||
| } catch (error) { | ||
| if (isAbortError(error)) { | ||
| if (abortedByTimeout) { | ||
| throw new Error('요청 시간이 초과되었습니다. 다시 시도해주세요.'); | ||
| } | ||
| throw new Error('요청이 취소되었습니다.'); | ||
| } | ||
| throw error; | ||
| } finally { | ||
| clearTimeout(timeoutId); | ||
| if (options.signal && abortHandler) { | ||
| options.signal.removeEventListener('abort', abortHandler); | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| const response = await request(); | ||
|
|
||
| if (!response.ok) { | ||
| const errorData: { message?: string; code?: string } = await response.json().catch(() => ({})); | ||
| const error = new Error(errorData.message || 'API 요청 중 오류가 발생했습니다.') as ApiError; | ||
| error.status = response.status; | ||
| error.code = errorData.code; | ||
|
|
||
| throw error; | ||
| } | ||
chldntjr1321 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return response.status === 204 ? (undefined as T) : response.json(); | ||
| }; | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| import { coreFetch } from '@/shared/apis/base/coreFetch'; | ||
|
|
||
| /** | ||
| * ### publicFetch | ||
| * | ||
| * @description | ||
| * - 비인증(public) API 호출을 위한 fetch 래퍼 함수입니다. | ||
| * | ||
| * @param endpoint | ||
| * - `/`로 시작하는 백엔드 API 엔드포인트 | ||
| * | ||
| * @param options | ||
| * - fetch에 전달할 RequestInit 옵션 | ||
| * | ||
| * @param timeoutMs | ||
| * - 요청 제한 시간(ms) | ||
| * - 지정하지 않으면 coreFetch의 기본 timeout을 사용합니다. | ||
| * | ||
| * @returns | ||
| * JSON 파싱된 응답 데이터 | ||
| */ | ||
| export const publicFetch = async <T>( | ||
| endpoint: string, | ||
| options: RequestInit = {}, | ||
| timeoutMs?: number | ||
| ): Promise<T> => { | ||
| const BASE_URL = process.env.NEXT_PUBLIC_API_URL; | ||
| if (!BASE_URL) { | ||
| throw new Error('NEXT_PUBLIC_API_URL 환경 변수가 설정되지 않았습니다.'); | ||
| } | ||
| const url = BASE_URL + endpoint; | ||
|
|
||
| return coreFetch<T>(url, options, timeoutMs); | ||
| }; | ||
chldntjr1321 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,26 +1,25 @@ | ||
| import { baseFetcher } from '@/shared/apis/base/baseFetcher'; | ||
| import type { LoginRequest } from '@/shared/types/auth.types'; | ||
| // import type { LoginRequest } from '@/shared/types/auth.types'; | ||
|
|
||
| /** | ||
| * 로그인 API | ||
| * 로그인 API (BFF) | ||
| * | ||
| * @param data - 로그인에 필요한 사용자 정보 | ||
| * @returns 로그인 API 응답 Promise | ||
| */ | ||
| export const logIn = (data: LoginRequest) => { | ||
| return baseFetcher('/auth/login', { | ||
| method: 'POST', | ||
| body: JSON.stringify(data), | ||
| }); | ||
| }; | ||
| // export const logIn = (data: LoginRequest) => { | ||
| // return baseFetcher('/auth/login', { | ||
| // method: 'POST', | ||
| // body: JSON.stringify(data), | ||
| // }); | ||
| // }; | ||
|
|
||
| /** | ||
| * 토큰 재발급 API | ||
| * 토큰 재발급 API (BFF) | ||
| * | ||
| * @returns 토큰 재발급 API 응답 Promise | ||
| */ | ||
| export const refreshToken = () => { | ||
| return baseFetcher('/auth/tokens', { | ||
| method: 'POST', | ||
| }); | ||
| }; | ||
| // export const refreshToken = () => { | ||
| // return baseFetcher('/auth/tokens', { | ||
| // method: 'POST', | ||
| // }); | ||
| // }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.