generated from pricelees/issue-pr-template
82 lines
2.4 KiB
TypeScript
82 lines
2.4 KiB
TypeScript
import axios, { type AxiosError, type AxiosRequestConfig, type Method } from 'axios';
|
|
|
|
const apiClient = axios.create({
|
|
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
|
timeout: 10000,
|
|
});
|
|
|
|
export const isLoginRequiredError = (error: any): boolean => {
|
|
if (!axios.isAxiosError(error) || !error.response) {
|
|
return false;
|
|
}
|
|
const LOGIN_REQUIRED_ERROR_CODE = ['A001', 'A002', 'A003', 'A006'];
|
|
const code = error.response?.data?.code;
|
|
return code && LOGIN_REQUIRED_ERROR_CODE.includes(code);
|
|
}
|
|
|
|
async function request<T>(
|
|
method: Method,
|
|
endpoint: string,
|
|
data: object = {},
|
|
isRequiredAuth: boolean = false
|
|
): Promise<T> {
|
|
const config: AxiosRequestConfig = {
|
|
method,
|
|
url: endpoint,
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
};
|
|
|
|
if (isRequiredAuth) {
|
|
const accessToken = localStorage.getItem('accessToken');
|
|
if (accessToken) {
|
|
if (!config.headers) {
|
|
config.headers = {};
|
|
}
|
|
config.headers['Authorization'] = `Bearer ${accessToken}`;
|
|
}
|
|
}
|
|
|
|
if (method.toUpperCase() !== 'GET') {
|
|
config.data = data;
|
|
}
|
|
|
|
try {
|
|
const response = await apiClient.request(config);
|
|
return response.data.data;
|
|
} catch (error: unknown) {
|
|
const axiosError = error as AxiosError<{ code: string, message: string }>;
|
|
console.error('API 요청 실패:', axiosError);
|
|
throw axiosError;
|
|
}
|
|
}
|
|
|
|
async function get<T>(endpoint: string, isRequiredAuth: boolean = false): Promise<T> {
|
|
return request<T>('GET', endpoint, {}, isRequiredAuth);
|
|
}
|
|
|
|
async function post<T>(endpoint: string, data: object = {}, isRequiredAuth: boolean = false): Promise<T> {
|
|
return request<T>('POST', endpoint, data, isRequiredAuth);
|
|
}
|
|
|
|
async function put<T>(endpoint: string, data: object = {}, isRequiredAuth: boolean = false): Promise<T> {
|
|
return request<T>('PUT', endpoint, data, isRequiredAuth);
|
|
}
|
|
|
|
async function patch<T>(endpoint: string, data: object = {}, isRequiredAuth: boolean = false): Promise<T> {
|
|
return request<T>('PATCH', endpoint, data, isRequiredAuth);
|
|
}
|
|
|
|
async function del<T>(endpoint: string, isRequiredAuth: boolean = false): Promise<T> {
|
|
return request<T>('DELETE', endpoint, {}, isRequiredAuth);
|
|
}
|
|
|
|
export default {
|
|
get,
|
|
post,
|
|
put,
|
|
patch,
|
|
del
|
|
};
|