-
Notifications
You must be signed in to change notification settings - Fork 3
fetch Instance 및 fetch 메서드 코드 구현 #95
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
15 commits
Select commit
Hold shift + click to select a range
01f6836
#70 refactor(fe): prettier printWidth 수정
KimKyuHoi c8ac06e
#70 feat(fe): fetch type 지정
KimKyuHoi 1145739
#70 feat(fe): 에러 메시지 객체리터럴화
KimKyuHoi 8e9a57b
#70 fetch(fe): fetchInstance 구현
KimKyuHoi 9a45bbc
#70 feat(fe): fetch 공용 메서드 구현
KimKyuHoi e663068
#70 feat(fe): 공용 모듈화 구현
KimKyuHoi 15c472d
#70 feat(fe): models 폴더명 변경
KimKyuHoi 3540f6c
#70 feat(fe): options 객체 jsdocs문서화
KimKyuHoi d2e0100
#70 feat(fe): tsDocs 문서화 및 주석 처리
KimKyuHoi cfc25e7
#70 fix(fe): 순환참조오류 해결
KimKyuHoi 8e14335
#70 fix(fe): 순환참조오류 버그 픽스
KimKyuHoi 84fa5a0
#70 perf(fe): dependabot vite 버전 업그레이드
KimKyuHoi b0c7904
#70 refactor(fe): 공용 타입 분리
KimKyuHoi e0cb43d
#70 refactor(fe): type 유니온화
KimKyuHoi b7bafd3
#70 fix(70): withToken -> includedAuthToken으로 객체명 변경
KimKyuHoi 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
There are no files selected for viewing
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
Empty file.
137 changes: 137 additions & 0 deletions
137
src/frontend/apps/web/src/shared/services/apis/fetch-instance.api.ts
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,137 @@ | ||
| import { ERROR_MESSAGES } from '@/src/shared/services/models'; | ||
| import type { | ||
| HttpMethod, | ||
| FetchOptions, | ||
| JsonValue, | ||
| ApiErrorResponse, | ||
| ApiResponse, | ||
| } from '@/src/shared/services/models'; | ||
|
|
||
| export async function fetchInstance<TResponse, TBody = JsonValue>( | ||
| url: string, | ||
| method: HttpMethod, | ||
| options: FetchOptions<TBody> = {}, | ||
| ): Promise<TResponse> { | ||
| try { | ||
| // 브라우저 환경에서만 localStorage 접근할 수 있도록 | ||
| const token = | ||
| typeof window !== 'undefined' ? localStorage.getItem('token') : null; | ||
|
|
||
| /** | ||
| * options 객체에서 필요한 값들을 구조분해할당합니다 | ||
| * @template TBody - 요청 본문의 타입 | ||
| * @typedef {object} ExtractedOptions | ||
| * @property {TBody} [body] - 요청 본문 데이터 | ||
| * @property {Record<string, string>} [params] - URL 쿼리 파라미터 | ||
| * @property {RequestCache} [cache] - Next.js 캐시 전략 | ||
| * @property {string[]} [tags] - 캐시 무효화 태그 | ||
| * @property {number} [revalidate] - 캐시 재검증 시간(초) | ||
| * @property {boolean} [includeAuthToken=true] - 토큰을 헤더에 추가할지 여부 | ||
| */ | ||
| const { | ||
| body, | ||
| params, | ||
| cache, | ||
| tags, | ||
| revalidate, | ||
| includeAuthToken = true, | ||
| ...restOptions | ||
| } = options; | ||
|
|
||
| // URL 쿼리 파라미터 추가 | ||
| const queryParams = params | ||
| ? `?${new URLSearchParams(params).toString()}` | ||
| : ''; | ||
| const finalUrl = `${url}${queryParams}`; | ||
|
|
||
| // 기본 헤더 설정 | ||
| const defaultHeaders: Record<string, string> = { | ||
| 'Content-Type': 'application/json', | ||
| ...(token ? { Authorization: `Bearer ${token}` } : {}), | ||
| }; | ||
|
|
||
| // includeAuthToken이 true일 때만 토큰을 헤더에 추가 | ||
| if (includeAuthToken) { | ||
| const token = | ||
| typeof window !== 'undefined' ? localStorage.getItem('token') : null; | ||
| if (token) { | ||
| defaultHeaders.Authorization = `Bearer ${token}`; | ||
| } | ||
| } | ||
|
|
||
| // 최종 fetch 옵션 구성 | ||
| const finalOptions: RequestInit = { | ||
| method, | ||
| ...restOptions, | ||
| headers: { | ||
| ...defaultHeaders, | ||
| ...(restOptions.headers as Record<string, string>), | ||
| }, | ||
| // cache, tags, revalidate 옵션이 있을 경우 next 프로퍼티에 추가 | ||
| ...(cache && { cache }), | ||
| ...(revalidate && { next: { revalidate } }), | ||
| ...(tags && { next: { tags } }), | ||
| }; | ||
|
|
||
| // body 데이터가 있고 GET 요청이 아닐 때만 body 필드 추가 | ||
| if (body && method !== 'GET') { | ||
| finalOptions.body = JSON.stringify(body); | ||
| } | ||
|
|
||
| const response = await fetch(finalUrl, finalOptions); | ||
|
|
||
| // 성공 응답 처리 | ||
| if (response.ok) { | ||
| const contentType = response.headers.get('content-type'); | ||
| // JSON 응답일 경우 JSON 파싱 | ||
| if (contentType?.includes('application/json')) { | ||
| const data = await response.json(); | ||
| // ApiResponse 형태로 응답이 왔다면 data 필드를 반환 | ||
| if ( | ||
| data && | ||
| typeof data === 'object' && | ||
| 'code' in data && | ||
| 'message' in data | ||
| ) { | ||
| // ApiResponse 형태면 data 필드만 추출 | ||
| return (data as ApiResponse<TResponse>).data as TResponse; | ||
| } | ||
| // 일반 JSON 응답이면 그대로 반환 | ||
| return data as TResponse; | ||
| } | ||
| // JSON이 아닌 경우 텍스트로 반환 | ||
| return response.text() as unknown as TResponse; | ||
| } | ||
|
|
||
| // 에러 응답 처리 | ||
| let errorResponse: ApiErrorResponse; | ||
| try { | ||
| errorResponse = (await response.json()) as ApiErrorResponse; | ||
| } catch { | ||
| // JSON 파싱 실패시 기본 에러 응답 생성 | ||
| errorResponse = { | ||
| code: String(response.status), | ||
| message: response.statusText || 'Unknown error occurred', | ||
| }; | ||
| } | ||
|
|
||
| // 커스텀 에러 객체 생성 | ||
| const error = new Error( | ||
| ERROR_MESSAGES[errorResponse.code] || errorResponse.message, | ||
| ) as Error & { | ||
| status: number; | ||
| code: string; | ||
| response: ApiErrorResponse; | ||
| }; | ||
|
|
||
| // 에러 객체에 상세 정보 추가 | ||
| error.status = response.status; | ||
| error.code = errorResponse.code; | ||
| error.response = errorResponse; | ||
|
|
||
| throw error; | ||
| } catch (error) { | ||
| console.error('fetchInstance error:', error); | ||
| throw error; | ||
| } | ||
| } | ||
157 changes: 157 additions & 0 deletions
157
src/frontend/apps/web/src/shared/services/apis/fetch-method.api.ts
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,157 @@ | ||
| import type { FetchOptions, JsonValue } from '@/src/shared/services/models'; | ||
|
|
||
| import { fetchInstance } from './fetch-instance.api'; | ||
|
|
||
| type RequestOptions<TBody = never> = Omit<FetchOptions<TBody>, 'body'>; | ||
|
|
||
| /** | ||
| * GET 요청을 보내는 함수입니다. | ||
| * @template TResponse - 응답 데이터의 타입 | ||
| * @typedef {object} GetRequestOptions | ||
| * @property {Record<string, string>} [params] - URL 쿼리 파라미터 | ||
| * @property {RequestCache} [cache] - Next.js의 캐시 전략 ('force-cache' | 'no-store' | 'no-cache') | ||
| * @property {string[]} [tags] - 캐시 무효화를 위한 태그 배열 | ||
| * @property {number} [revalidate] - 캐시 재검증 주기(초) | ||
| * @property {boolean} [includeAuthToken] - 인증 토큰 사용 여부 | ||
| * | ||
| * @param {string} url - API 엔드포인트 URL | ||
| * @param {Omit<FetchOptions, 'body'>} [options] - GET 요청 옵션 | ||
| * @returns {Promise<TResponse>} 응답 데이터를 포함한 Promise | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * // 기본 GET 요청 | ||
| * const data = await getRequest<UserData>('/api/users/me'); | ||
| * | ||
| * // 쿼리 파라미터와 캐시 옵션과 토큰이 없을때 GET 요청 | ||
| * const users = await getRequest<User[]>('/api/users', { | ||
| * params: { page: '1', size: '10' }, | ||
| * cache: 'force-cache', | ||
| * tags: ['users'], | ||
| * includeAuthToken: false, | ||
| * }); | ||
| * ``` | ||
| * | ||
| * * GET 요청을 보내는 함수입니다. | ||
| * @throws {ApiError} API 요청이 실패했을 때 발생합니다 (예: 400, 401, 404 등) | ||
| * @throws {NetworkError} 네트워크 연결에 문제가 있을 때 발생합니다 | ||
| */ | ||
|
|
||
| export async function getRequest<TResponse>( | ||
KimKyuHoi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| url: string, | ||
| options?: RequestOptions, | ||
| ): Promise<TResponse> { | ||
| return fetchInstance<TResponse>(url, 'GET', options); | ||
| } | ||
|
|
||
| /** | ||
| * POST 요청을 보내는 함수입니다. | ||
| * @template TResponse - 응답 데이터의 타입 | ||
| * @template TBody - 요청 본문의 타입 | ||
| * @typedef {object} PostRequestOptions | ||
| * @property {Record<string, string>} [params] - URL 쿼리 파라미터 | ||
| * @property {string[]} [tags] - 캐시 무효화를 위한 태그 배열 | ||
| * @property {boolean} [includeAuthToken] - 인증 토큰 사용 여부 | ||
| * | ||
| * @param {string} url - API 엔드포인트 URL | ||
| * @param {TBody} body - 전송할 데이터 | ||
| * @param {Omit<FetchOptions<TBody>, 'body'>} [options] - POST 요청 옵션 | ||
| * @returns {Promise<TResponse>} 응답 데이터를 포함한 Promise | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * // 사용자 생성 요청 | ||
| * const newUser = await postRequest<User, CreateUserDto>( | ||
| * '/api/users', | ||
| * { name: 'John', email: '[email protected]' } | ||
| * ); | ||
| * ``` | ||
| * | ||
| * * POST 요청을 보내는 함수입니다. | ||
| * @throws {ApiError} API 요청이 실패했을 때 발생합니다 (예: 400, 401, 404 등) | ||
| * @throws {NetworkError} 네트워크 연결에 문제가 있을 때 발생합니다 | ||
| */ | ||
|
|
||
| export async function postRequest<TResponse, TBody = JsonValue>( | ||
| url: string, | ||
| body: TBody, | ||
| options?: RequestOptions<TBody>, | ||
| ): Promise<TResponse> { | ||
| return fetchInstance<TResponse, TBody>(url, 'POST', { ...options, body }); | ||
| } | ||
|
|
||
| /** | ||
| * PATCH 요청을 보내는 함수입니다. | ||
| * @template TResponse - 응답 데이터의 타입 | ||
| * @template TBody - 요청 본문의 타입 | ||
| * @typedef {object} PatchRequestOptions | ||
| * @property {Record<string, string>} [params] - URL 쿼리 파라미터 | ||
| * @property {string[]} [tags] - 캐시 무효화를 위한 태그 배열 | ||
| * @property {boolean} [includeAuthToken] - 인증 토큰 사용 여부 | ||
| * | ||
| * @param {string} url - API 엔드포인트 URL | ||
| * @param {TBody} body - 업데이트할 데이터 | ||
| * @param {Omit<FetchOptions<TBody>, 'body'>} [options] - PATCH 요청 옵션 | ||
| * @returns {Promise<TResponse>} 응답 데이터를 포함한 Promise | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * // 사용자 정보 업데이트 | ||
| * const updatedUser = await patchRequest<User, UpdateUserDto>( | ||
| * `/api/users/${userId}`, | ||
| * { name: 'Updated Name' }, | ||
| * { tags: ['user-profile'] } | ||
| * ); | ||
| * ``` | ||
| * | ||
| * * PATCH 요청을 보내는 함수입니다. | ||
| * @throws {ApiError} API 요청이 실패했을 때 발생합니다 (예: 400, 401, 404 등) | ||
| * @throws {NetworkError} 네트워크 연결에 문제가 있을 때 발생합니다 | ||
| * | ||
| */ | ||
| export async function patchRequest<TResponse, TBody = JsonValue>( | ||
| url: string, | ||
| body: TBody, | ||
| options?: RequestOptions<TBody>, | ||
| ): Promise<TResponse> { | ||
| return fetchInstance<TResponse, TBody>(url, 'PATCH', { ...options, body }); | ||
| } | ||
|
|
||
| /** | ||
| * DELETE 요청을 보내는 함수입니다. | ||
| * @template TResponse - 응답 데이터의 타입 | ||
| * @template TBody - 요청 본문의 타입 | ||
| * @typedef {object} DeleteRequestOptions | ||
| * @property {Record<string, string>} [params] - URL 쿼리 파라미터 | ||
| * @property {string[]} [tags] - 캐시 무효화를 위한 태그 배열 | ||
| * @property {boolean} [includeAuthToken] - 인증 토큰 사용 여부 | ||
| * | ||
| * @param {string} url - API 엔드포인트 URL | ||
| * @param {TBody} [body] - 전송할 데이터 (선택사항) | ||
| * @param {Omit<FetchOptions<TBody>, 'body'>} [options] - DELETE 요청 옵션 | ||
| * @returns {Promise<TResponse>} 응답 데이터를 포함한 Promise | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * // 단순 삭제 요청 | ||
| * await deleteRequest<void>(`/api/posts/${postId}`); | ||
| * | ||
| * // 본문과 함께 삭제 요청 | ||
| * await deleteRequest<void, DeletePostDto>( | ||
| * `/api/posts/${postId}`, | ||
| * { reason: 'spam' }, | ||
| * { tags: ['posts'] } | ||
| * ); | ||
| * ``` | ||
| * | ||
| * * DELETE 요청을 보내는 함수입니다. | ||
| * @throws {ApiError} API 요청이 실패했을 때 발생합니다 (예: 400, 401, 404 등) | ||
| * @throws {NetworkError} 네트워크 연결에 문제가 있을 때 발생합니다 | ||
| */ | ||
| export async function deleteRequest<TResponse, TBody = JsonValue>( | ||
| url: string, | ||
| body?: TBody, | ||
| options?: RequestOptions<TBody>, | ||
| ): Promise<TResponse> { | ||
| return fetchInstance<TResponse, TBody>(url, 'DELETE', { ...options, body }); | ||
| } | ||
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,7 @@ | ||
| export { fetchInstance } from './fetch-instance.api'; | ||
| export { | ||
| getRequest, | ||
| postRequest, | ||
| patchRequest, | ||
| deleteRequest, | ||
| } from './fetch-method.api'; |
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,2 @@ | ||
| export * from './apis'; | ||
| export * from './models'; |
23 changes: 23 additions & 0 deletions
23
src/frontend/apps/web/src/shared/services/models/error/authorization-errors.ts
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,23 @@ | ||
| export type AuthErrorCode = keyof typeof AUTH_ERROR_MESSAGES; | ||
|
|
||
| export const AUTH_ERROR_MESSAGES: Record<string, string> = { | ||
| A40000: '요청한 값이 유효하지 않습니다.', | ||
| A40001: '잘못된 요청입니다.', | ||
| A40002: '필수 헤더가 누락되었습니다.', | ||
| A40003: '필수 파라미터가 누락되었습니다.', | ||
| A40004: '인가 코드가 만료되었습니다.', | ||
| A40005: '로그인 요청이 유효하지 않습니다.', | ||
|
|
||
| A40100: '액세스 토큰이 만료되었습니다.', | ||
| A40101: '리프레시 토큰이 만료되었습니다.', | ||
| A40102: '리프레시 토큰이 유효하지 않습니다.', | ||
| A40103: '유효하지 않은 토큰입니다.', | ||
| A40104: '해당 유저의 리프레시 토큰이 존재하지 않습니다.', | ||
|
|
||
| A40400: '존재하지 않는 API입니다.', | ||
| A40401: '해당 유저는 존재하지 않습니다.', | ||
|
|
||
| A40500: '지원하지 않는 메소드입니다.', | ||
|
|
||
| A50000: '서버 내부 오류입니다.', | ||
| } as const; |
11 changes: 11 additions & 0 deletions
11
src/frontend/apps/web/src/shared/services/models/error/index.ts
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,11 @@ | ||
| import { AUTH_ERROR_MESSAGES } from './authorization-errors'; | ||
| import type { AuthErrorCode } from './authorization-errors'; | ||
| import { WORKSPACE_ERROR_MESSAGES } from './workspace-errors'; | ||
| import type { WorkspaceErrorCode } from './workspace-errors'; | ||
|
|
||
| export type ErrorCode = AuthErrorCode | WorkspaceErrorCode; | ||
|
|
||
| export const ERROR_MESSAGES: Record<string, string> = { | ||
| ...AUTH_ERROR_MESSAGES, | ||
| ...WORKSPACE_ERROR_MESSAGES, | ||
| }; |
22 changes: 22 additions & 0 deletions
22
src/frontend/apps/web/src/shared/services/models/error/workspace-errors.ts
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,22 @@ | ||
| export type WorkspaceErrorCode = keyof typeof WORKSPACE_ERROR_MESSAGES; | ||
|
|
||
| export const WORKSPACE_ERROR_MESSAGES: Record<string, string> = { | ||
| W00001: '알 수 없는 에러가 발생했습니다.', | ||
| W40001: '잘못된 요청입니다.', | ||
| W40002: '유효성 검증에 실패했습니다.', | ||
| W40003: '필수 파라미터가 누락되었습니다.', | ||
| W40004: '잘못된 파라미터가 포함되었습니다.', | ||
| W40005: '동일한 채널명이 이미 해당 워크스페이스에 존재합니다.', | ||
| W40006: '유저가 이미 해당 채널에 참여하고 있습니다', | ||
|
|
||
| W40401: '등록되지 않은 워크스페이스입니다.', | ||
| W40402: '등록되지 않은 채널입니다.', | ||
| W40403: '등록되지 않은 유저입니다.', | ||
|
|
||
| W50001: '서버 내부 오류가 발생했습니다.', | ||
| W50002: '데이터베이스 처리 중 오류가 발생했습니다.', | ||
| W50003: '파일 업로드에 실패했습니다.', | ||
| W50004: '파일 다운로드 중 오류가 발생했습니다.', | ||
| W50005: '파일 처리 중 오류가 발생했습니다.', | ||
| W50006: '예상치 못한 오류가 발생했습니다.', | ||
| } as const; |
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,2 @@ | ||
| export * from './error'; | ||
| export * from './types'; |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
withToken 일 때 token이 없다면 의도치 않은 요청이 아닐까요? 에러가 나타나면 좋을 듯합니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
오 제가 생각했던 부분은 token을 넣어야할 api와 넣지 말아야할 api를 구분지어서 request를 보내기 위해서 짠 코드긴 했습니다.
저희가 메인 페이지 내에서 주식 데이터를 불러올때 로그인없이도 받아올 수 있다보니 그랬던 것 같습니다 (:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
위에서 봤을 때는 withToken을 명시해야 되는 거 같아서 없다면 에러가 발생해야 하지 않을까라는 생각이 있긴 했네요
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
오호 뭔가 헷갈릴수도 있겠단 생각이 드네요. 객체명을 바꾸던가 조금 개선을 해야되겠군요
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저도 비슷한 생각입니다!
저는 단순하게 생각하여 token이 없다면 에러처리를 해야할것같은데, token을 넣지 말아야할 api는 어떤것이 있을지 궁급합니다!
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@KimKyuHoi 그리고 리뷰가 아닌 단순한 궁금증인데, token관련한 코드가 3번 정도 나타나는데 보통 그런식으로 여러번 확인하고 할당하는걸까요?
처음 변수 선언때도 localstorage에서 받아오고 아래 withtoken에 의해 또한번 받아오면서, header를 선언하는 부분도 token의 여부에 따라 달라지는 것이 두번 반복되는것으로 보여서요!
제가 instance는 해본적이 없어서 다 다른 경우에 대응하기 위한 부분일까요?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
초기 로그인같은 경우는 토큰없이 쓰기때문에 넣긴 했습니다.
그리고 첫번째 토큰 로직은 저희가 스토리지 내에서 토큰을 가지고 오기로 결정했으므로 스토리지에서 토큰을 받아오는 로직입니다.
두번쨰 로직은 저희가 토큰을 쓸껀지 안 쓸껀지 확인하는 로직이구요. default는 true이나 false설정을 걸 경우 토큰을 안 쓸 수 있습니다.
세번째 로직은 가지고 온 토큰을 header내에 Authorization Bearer에 넣는 로직입니다.
제가 로직 관련해서 주석처리를 해놓긴 했는데 나중에 궁금해시면 주석처리한 부분 따라 읽으면서 코드 내려가시면 읽기 편하실껍니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@handje 객체명 교체하였습니다~ withToken -> includedAuthToken으로 교체했습니다~