diff --git a/src/libs/axios.ts b/src/libs/axios.ts index 4fa4554..9f3aa8d 100644 --- a/src/libs/axios.ts +++ b/src/libs/axios.ts @@ -22,9 +22,43 @@ axiosInstance.interceptors.request.use( // Response interceptor axiosInstance.interceptors.response.use( - (response) => response, + (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('_', '')) +}