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

chore: 배포 환경에서 AxiosInterceptor 설정 #219

Merged
merged 3 commits into from
Nov 14, 2024

Conversation

WonJuneKim
Copy link
Collaborator

@WonJuneKim WonJuneKim commented Nov 14, 2024

💡 작업 내용

  • 설정 파일(package.json, package-lock.json, webpack.config.js, index.html) 이름을 PICK-O 로 변경
  • production 환경에서 baseUrl 설정 추가

💡 자세한 설명

✅ Intercepter.ts(src/api/intercepter)

  baseURL: process.env.MSW ? process.env.API_URL : '/api',

기존에는 MSW 유무에 따라 baseUrl을 분기처리 하였고, MSW를 사용하지 않는 경우 webpack.config.js에서 설정해준 프록시 주소로 연결하는 로직이 구현되어 있었습니다.

현재는 msw를 사용하지 않기 때문에

const baseURL =
  process.env.NODE_ENV === 'production' ? process.env.API_URL : '/api';

와 같이 build 환경이 development 유무에 따라 baseUrl을 분기처리 하였습니다.

✅ 설정 파일 네이밍 수정

  • package.json 의 경우 대문자 입력이 불가능하여 PICK-O 가 아닌 pick-o로 수정하였습니다.
  • package-lock.json은 직접 수정이 아닌 package.json 수정 후 npm install을 통해 수정하였습니다.

📗 참고 자료 (선택)

📢 리뷰 요구 사항(선택)

🚩 후속 작업 (선택)

✅ 셀프 체크리스트

  • PR 제목을 형식에 맞게 작성했나요?
  • 브랜치 전략에 맞는 브랜치에 PR을 올리고 있나요? (master/main이 아닙니다.)
  • 이슈는 close 했나요?
  • Reviewers, Labels, Projects를 등록했나요?
  • 작업 도중 문서 수정이 필요한 경우 잘 수정했나요?
  • 테스트는 잘 통과했나요?
  • 불필요한 코드는 제거했나요?

closes #218

Summary by CodeRabbit

  • 새로운 기능

    • 프로젝트 이름이 "balance-talk"에서 "PICK-O"로 변경되었습니다.
    • 웹페이지 제목이 "BalanceTalk"에서 "PICK-O"로 업데이트되었습니다.
    • HTML 문서의 언어 속성이 "en"에서 "ko"로 변경되었습니다.
  • 버그 수정

    • API 엔드포인트 구성의 유연성을 향상시켰습니다.
  • 문서화

    • 변경된 프로젝트 이름과 관련된 메타데이터가 업데이트되었습니다.

@WonJuneKim WonJuneKim added ⚙️chore 세팅 관련 👩🏻‍💻 frontend 프론트엔드 작업 labels Nov 14, 2024
@WonJuneKim WonJuneKim self-assigned this Nov 14, 2024
Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

이 변경 사항은 프로젝트의 이름을 "balance-talk"에서 "pick-o"로 변경하고, HTML 문서의 언어 속성을 영어에서 한국어로 수정하며, Axios 인스턴스의 기본 URL 설정을 환경에 따라 조정하는 내용을 포함합니다. 또한, Webpack 구성 파일에서도 프로젝트 이름 변경과 환경 설정 로직의 간소화가 이루어졌습니다. 전반적으로, 이러한 변경은 프로젝트의 리브랜딩과 환경 처리 개선을 목표로 하고 있습니다.

Changes

파일 변경 요약
package.json 프로젝트 이름을 "balance-talk"에서 "pick-o"로 변경
public/index.html HTML 언어 속성을 lang="en"에서 lang="ko"로 변경; 제목을 "BalanceTalk"에서 "PICK-O"로 변경
src/api/interceptor.ts Axios 인스턴스의 baseURL을 환경에 따라 설정하도록 수정
webpack.config.js 프로젝트 이름을 'balance-talk'에서 'PICK-O'로 변경; 환경 설정 로직 간소화

Assessment against linked issues

Objective Addressed Explanation
production 시 연결되는 baseUrl 추가 ( #218 )
axios Interceptor 로직 분기 추가 ( #218 )

🐇 변화의 바람이 불어와
이름도 바뀌고, 언어도 바뀌고,
API의 길도 새롭게 열려
PICK-O로 달려가요, 함께 가요!
🥕✨


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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@areumH areumH self-requested a review November 14, 2024 15:56
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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을 통해 환경 변수를 주입하고 있습니다. 보안과 유지보수성을 위해 다음과 같은 개선을 제안드립니다:

  1. 필수 환경 변수 목록을 명시적으로 관리
  2. 환경 변수 누락 시 빌드 단계에서 오류 발생하도록 설정
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: 로깅 개선 및 코드 구조화 필요

  1. 개발용 console.log는 제거하거나 proper 로깅으로 대체해주세요.
  2. 인터셉터 로직을 더 작은 함수들로 분리하면 가독성이 향상될 것 같습니다.
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

📥 Commits

Reviewing files that changed from the base of the PR and between 62ce00c and a960097.

⛔ 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 목적에 맞게 다음 사항들을 확인해주세요:

  1. API_URL이 프로덕션 환경에서 올바르게 설정되어 있는지
  2. 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 순으로 되어있는데, 프로덕션 환경에서의 안정성을 위해 다음 사항들을 확인해주세요:

  1. 환경 변수 파일이 누락된 경우의 폴백(fallback) 처리
  2. 각 환경 변수 파일에 필수 값들이 올바르게 설정되어 있는지 여부

19-19: 프로젝트 이름 변경 확인

프로젝트 이름이 'PICK-O'로 변경되었습니다. 이 변경이 다음 파일들에도 일관되게 적용되었는지 확인이 필요합니다:

  • package.json
  • public/index.html
  • 기타 설정 파일들

Comment on lines +51 to +83
// 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);
},
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

토큰 갱신 로직 및 에러 처리 개선 필요

  1. 주석 처리된 토큰 갱신 로직에 대한 명확한 방향이 필요합니다:

    • 완전히 제거하거나
    • 구현을 완료하거나
    • TODO 주석으로 향후 계획을 명시해주세요
  2. 에러 처리를 더 구체적으로 개선할 수 있습니다:

    • 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);
  }
};

Comment on lines +12 to +13
const baseURL =
process.env.NODE_ENV === 'production' ? process.env.API_URL : '/api';
Copy link
Contributor

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일 경우 문제가 발생할 수 있습니다. 다음 사항들을 고려해주세요:

  1. 환경 변수 타입 선언 추가
  2. 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

Copy link
Collaborator

@alwubin alwubin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드가 even하게 익었네요. approve 드릴게요~

@WonJuneKim WonJuneKim merged commit 095a4ff into dev Nov 14, 2024
3 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⚙️chore 세팅 관련 👩🏻‍💻 frontend 프론트엔드 작업
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

배포 환경에서의 AxiosInterceptor 설정
3 participants