-
Notifications
You must be signed in to change notification settings - Fork 1
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
chore: 배포 환경에서 AxiosInterceptor 설정 #219
Conversation
Caution Review failedThe pull request is closed. Walkthrough이 변경 사항은 프로젝트의 이름을 "balance-talk"에서 "pick-o"로 변경하고, HTML 문서의 언어 속성을 영어에서 한국어로 수정하며, Axios 인스턴스의 기본 URL 설정을 환경에 따라 조정하는 내용을 포함합니다. 또한, Webpack 구성 파일에서도 프로젝트 이름 변경과 환경 설정 로직의 간소화가 이루어졌습니다. 전반적으로, 이러한 변경은 프로젝트의 리브랜딩과 환경 처리 개선을 목표로 하고 있습니다. Changes
Assessment against linked issues
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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.
Actionable comments posted: 2
🧹 Outside diff range and nitpick comments (3)
webpack.config.js (1)
Line range hint
76-81
: 환경 변수 주입 설정 개선 필요현재 EnvironmentPlugin과 DefinePlugin을 통해 환경 변수를 주입하고 있습니다. 보안과 유지보수성을 위해 다음과 같은 개선을 제안드립니다:
- 필수 환경 변수 목록을 명시적으로 관리
- 환경 변수 누락 시 빌드 단계에서 오류 발생하도록 설정
plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', }), - new webpack.EnvironmentPlugin(['API_URL']), + new webpack.EnvironmentPlugin({ + API_URL: undefined, // undefined로 설정하면 필수 값으로 처리됨 + }), new webpack.DefinePlugin({ 'process.env.MSW': env.MSW, }), ],src/api/interceptor.ts (2)
15-24
: 주석 처리된 코드 정리 필요더 이상 사용하지 않는 baseURL 설정 주석은 제거하는 것이 좋습니다.
export const axiosInstance = axios.create({ - // baseURL: process.env.API_URL, - // baseURL: '/api', baseURL, headers: { 'Content-Type': 'application/json', }, withCredentials: true, timeout: AXIOS.TIMEOUT, });
27-49
: 로깅 개선 및 코드 구조화 필요
- 개발용 console.log는 제거하거나 proper 로깅으로 대체해주세요.
- 인터셉터 로직을 더 작은 함수들로 분리하면 가독성이 향상될 것 같습니다.
axiosInstance.interceptors.request.use( (config: InternalAxiosRequestConfig) => { if (config.headers.Authorization) return config; const { accessToken } = store.getState().token; const newConfig = { ...config }; + const setFileUploadHeaders = (config: InternalAxiosRequestConfig) => { + if (config.url === END_POINT.FILE_UPLOAD) { + config.headers['Content-Type'] = 'multipart/form-data'; + } + }; + const setAuthorizationHeader = (config: InternalAxiosRequestConfig, token: string) => { + if (token) { + config.headers.Authorization = `Bearer ${token}`; + } + }; - if (newConfig.url === END_POINT.FILE_UPLOAD) { - newConfig.headers['Content-Type'] = 'multipart/form-data'; - } - if (accessToken) { - newConfig.headers.Authorization = `Bearer ${accessToken}`; - } + setFileUploadHeaders(newConfig); + setAuthorizationHeader(newConfig, accessToken); - // console.log('요청 전 config', newConfig); return newConfig; }, (error: AxiosError<AxiosErrorResponse>) => { - // console.log('요청 전 config 에러'); return Promise.reject(error); }, );
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (1)
package-lock.json
is excluded by!**/package-lock.json
📒 Files selected for processing (4)
package.json
(1 hunks)public/index.html
(1 hunks)src/api/interceptor.ts
(1 hunks)webpack.config.js
(1 hunks)
✅ Files skipped from review due to trivial changes (2)
- package.json
- public/index.html
🔇 Additional comments (3)
webpack.config.js (3)
Line range hint 90-103
: 프록시 설정 검토 필요
프록시 설정에서 API_URL을 사용하는 부분이 있습니다. PR 목적에 맞게 다음 사항들을 확인해주세요:
- API_URL이 프로덕션 환경에서 올바르게 설정되어 있는지
- pathRewrite 설정이 AxiosInterceptor의 baseURL 설정과 일치하는지
#!/bin/bash
# API 관련 설정 검색
echo "Checking API related configurations..."
rg -A 5 "API_URL|baseURL|axios" --type ts --type js
Line range hint 8-18
: 환경 설정 로직 검토 필요
환경 변수 설정 로직이 MSW, DEV, Production 순으로 되어있는데, 프로덕션 환경에서의 안정성을 위해 다음 사항들을 확인해주세요:
- 환경 변수 파일이 누락된 경우의 폴백(fallback) 처리
- 각 환경 변수 파일에 필수 값들이 올바르게 설정되어 있는지 여부
19-19
: 프로젝트 이름 변경 확인
프로젝트 이름이 'PICK-O'로 변경되었습니다. 이 변경이 다음 파일들에도 일관되게 적용되었는지 확인이 필요합니다:
- package.json
- public/index.html
- 기타 설정 파일들
// response interceptor (after request) | ||
axiosInstance.interceptors.response.use( | ||
(response) => { | ||
// console.log('요청 후 response'); | ||
return response; | ||
}, | ||
(error: AxiosError<AxiosErrorResponse>) => { | ||
// console.log('요청 후 response 에러'); | ||
const originalRequest = error.config; | ||
if (!error.response || !originalRequest) throw error; | ||
|
||
const { data, status } = error.response; | ||
// const refreshToken = localStorage.getItem('rtk'); | ||
|
||
// if (refreshToken) { | ||
// if (status === HTTP_STATUS_CODE.UNAUTHORIZED) { | ||
// const accessToken = getRefreshToken(); | ||
// console.log('new accessToken: ', accessToken); | ||
// localStorage.setItem('accessToken', accessToken); | ||
// store.dispatch({ type: 'token/setAccessToken', payload: accessToken }); | ||
// originalRequest.headers.Authorization = `Bearer ${accessToken}`; | ||
// return axiosInstance(originalRequest); | ||
// console.log('토큰 재발급'); | ||
// } | ||
// if (status === HTTP_STATUS_CODE.BAD_REQUEST) { | ||
// localStorage.removeItem('accessToken'); | ||
// localStorage.removeItem('rtk'); | ||
// window.location.href = '/'; | ||
// } | ||
// } | ||
throw new HTTPError(status, data.httpStatus, data.message); | ||
}, | ||
); |
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.
토큰 갱신 로직 및 에러 처리 개선 필요
-
주석 처리된 토큰 갱신 로직에 대한 명확한 방향이 필요합니다:
- 완전히 제거하거나
- 구현을 완료하거나
- TODO 주석으로 향후 계획을 명시해주세요
-
에러 처리를 더 구체적으로 개선할 수 있습니다:
- HTTP 상태 코드별 처리 로직 분리
- 사용자 친화적인 에러 메시지 처리
에러 처리 개선 예시:
const handleResponseError = (error: AxiosError<AxiosErrorResponse>) => {
if (!error.response) {
throw new HTTPError(500, 'NETWORK_ERROR', '네트워크 연결을 확인해주세요');
}
const { status, data } = error.response;
switch (status) {
case 401:
// 인증 에러 처리
break;
case 403:
// 권한 에러 처리
break;
default:
throw new HTTPError(status, data.httpStatus, data.message);
}
};
const baseURL = | ||
process.env.NODE_ENV === 'production' ? process.env.API_URL : '/api'; |
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.
💡 Codebase verification
환경 변수 타입 정의와 검증 로직이 필요합니다
코드베이스 분석 결과, process.env.API_URL
이 여러 곳에서 사용되고 있으나 타입 정의와 유효성 검증이 누락되어 있습니다:
src/api/interceptor.ts
에서 production 환경일 때API_URL
사용webpack.config.js
의 프록시 설정- Mock 핸들러들과 소셜 로그인에서도 사용
다음 작업이 필요합니다:
env.d.ts
파일에API_URL
환경 변수 타입 선언 추가- Production 환경에서
API_URL
값 존재 여부 검증 로직 구현 - 환경 변수 부재 시 기본값 또는 에러 처리 추가
🔗 Analysis chain
환경 변수 타입 안전성 및 유효성 검증 필요
process.env.API_URL
이 production 환경에서 undefined일 경우 문제가 발생할 수 있습니다. 다음 사항들을 고려해주세요:
- 환경 변수 타입 선언 추가
- API_URL 존재 여부 검증
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: API_URL 환경 변수가 .env 파일에 정의되어 있는지 확인
# .env 파일들 검색
fd -t f "^.env" -x cat {} \; | grep "API_URL"
Length of output: 48
Script:
#!/bin/bash
# Check for environment variable usage in TypeScript files
rg "process\.env\.API_URL" -A 2 -B 2
# Check for environment type declarations
fd -e ts -e d.ts | xargs rg "declare global.*ProcessEnv|interface ProcessEnv"
# Check for environment setup files
fd "\.env" --hidden
Length of output: 3583
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.
코드가 even하게 익었네요. approve 드릴게요~
Quality Gate passedIssues Measures |
💡 작업 내용
PICK-O
로 변경💡 자세한 설명
✅ Intercepter.ts(src/api/intercepter)
기존에는 MSW 유무에 따라 baseUrl을 분기처리 하였고, MSW를 사용하지 않는 경우
webpack.config.js
에서 설정해준 프록시 주소로 연결하는 로직이 구현되어 있었습니다.현재는 msw를 사용하지 않기 때문에
와 같이 build 환경이
development
유무에 따라 baseUrl을 분기처리 하였습니다.✅ 설정 파일 네이밍 수정
PICK-O
가 아닌pick-o
로 수정하였습니다.📗 참고 자료 (선택)
📢 리뷰 요구 사항(선택)
🚩 후속 작업 (선택)
✅ 셀프 체크리스트
closes #218
Summary by CodeRabbit
새로운 기능
버그 수정
문서화