67 lines
1.6 KiB
TypeScript
67 lines
1.6 KiB
TypeScript
import axios from 'axios'
|
|
|
|
export const axiosInstance = (url: string | null | undefined) => {
|
|
const baseURL = url || process.env.NEXT_PUBLIC_API_URL
|
|
|
|
return axios.create({
|
|
baseURL,
|
|
headers: {
|
|
Accept: 'application/json',
|
|
},
|
|
})
|
|
}
|
|
|
|
// Request interceptor
|
|
axios.interceptors.request.use(
|
|
(config) => {
|
|
// 여기에 토큰 추가 등의 공통 로직을 넣을 수 있습니다
|
|
return config
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error)
|
|
},
|
|
)
|
|
|
|
// Response interceptor
|
|
axios.interceptors.response.use(
|
|
(response) => transferResponse(response),
|
|
(error) => {
|
|
// 에러 처리 로직
|
|
return Promise.reject(error)
|
|
},
|
|
)
|
|
|
|
// response데이터가 array, object에 따라 분기하여 키 변환
|
|
const transferResponse = (response: any) => {
|
|
if (!response.data) return response.data
|
|
|
|
// 배열인 경우 각 객체의 키를 변환
|
|
if (Array.isArray(response.data)) {
|
|
return response.data.map((item: any) => transformObjectKeys(item))
|
|
}
|
|
|
|
// 단일 객체인 경우
|
|
return transformObjectKeys(response.data)
|
|
}
|
|
|
|
// camel case object 반환
|
|
const transformObjectKeys = (obj: any): any => {
|
|
if (Array.isArray(obj)) {
|
|
return obj.map(transformObjectKeys)
|
|
}
|
|
|
|
if (obj !== null && typeof obj === 'object') {
|
|
return Object.keys(obj).reduce((acc: any, key: string) => {
|
|
const camelKey = snakeToCamel(key)
|
|
acc[camelKey] = transformObjectKeys(obj[key])
|
|
return acc
|
|
}, {})
|
|
}
|
|
|
|
return obj
|
|
}
|
|
// snake case to camel case
|
|
const snakeToCamel = (str: string): string => {
|
|
return str.replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace('-', '').replace('_', ''))
|
|
}
|