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
Merged
Show file tree
Hide file tree
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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "balance-talk",
"name": "pick-o",
"version": "1.0.0",
"description": "",
"main": "index.js",
Expand Down
4 changes: 2 additions & 2 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<html lang="en">
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>BalanceTalk</title>
<title>PICK-O</title>
</head>

<body>
Expand Down
163 changes: 83 additions & 80 deletions src/api/interceptor.ts
Original file line number Diff line number Diff line change
@@ -1,80 +1,83 @@
import store from '@/store';
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
import { AXIOS, END_POINT } from '../constants/api';
import { HTTPError } from './HttpError';

export interface AxiosErrorResponse {
status: number;
httpStatus?: string;
message?: string;
}

export const axiosInstance = axios.create({
// baseURL: process.env.API_URL,
// baseURL: '/api',
baseURL: process.env.MSW ? process.env.API_URL : '/api',
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
timeout: AXIOS.TIMEOUT,
});

// request interceptor (before request)
axiosInstance.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
if (config.headers.Authorization) return config;

const { accessToken } = store.getState().token;
const newConfig = { ...config };

if (newConfig.url === END_POINT.FILE_UPLOAD) {
newConfig.headers['Content-Type'] = 'multipart/form-data';
}
if (accessToken) {
newConfig.headers.Authorization = `Bearer ${accessToken}`;
}

// console.log('요청 전 config', newConfig);
return newConfig;
},
(error: AxiosError<AxiosErrorResponse>) => {
// console.log('요청 전 config 에러');

return Promise.reject(error);
},
);

// 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);
},
);
import store from '@/store';
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
import { AXIOS, END_POINT } from '../constants/api';
import { HTTPError } from './HttpError';

export interface AxiosErrorResponse {
status: number;
httpStatus?: string;
message?: string;
}

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

Comment on lines +12 to +13
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

export const axiosInstance = axios.create({
// baseURL: process.env.API_URL,
// baseURL: '/api',
baseURL,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
timeout: AXIOS.TIMEOUT,
});

// request interceptor (before request)
axiosInstance.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
if (config.headers.Authorization) return config;

const { accessToken } = store.getState().token;
const newConfig = { ...config };

if (newConfig.url === END_POINT.FILE_UPLOAD) {
newConfig.headers['Content-Type'] = 'multipart/form-data';
}
if (accessToken) {
newConfig.headers.Authorization = `Bearer ${accessToken}`;
}

// console.log('요청 전 config', newConfig);
return newConfig;
},
(error: AxiosError<AxiosErrorResponse>) => {
// console.log('요청 전 config 에러');

return Promise.reject(error);
},
);

// 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);
},
);
2 changes: 1 addition & 1 deletion webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ module.exports = (env) => {
}

return {
name: 'balance-talk',
name: 'PICK-O',
mode: DEV ? 'development' : 'production',
entry: './src/index.tsx',
module: {
Expand Down
Loading