import axios, { Axios } from 'axios' const AxiosType = { INTERNAL: 'Internal', EXTERNAL: 'External', } /** * axios 인스턴스 생성 후 반환 * @param {String} lang * @returns http request instance - get, post, put, patch, delete (promise 접수사가 붙은 함수는 promise 반환) */ export function useAxios(lang = '') { const getInstances = (url) => { /** * url이 http로 시작하면 외부 서버로 판단 */ let type = AxiosType.INTERNAL url.startsWith('http') ? (type = AxiosType.EXTERNAL) : '' /** * 내부 서버로 요청 시 lang 헤더 추가 */ let headerValue = { Accept: 'application/json', } url.startsWith('https') ? '' : (headerValue['lang'] = lang) return axios.create({ baseURL: type === AxiosType.INTERNAL ? process.env.NEXT_PUBLIC_API_SERVER_PATH : '', headers: headerValue, }) } // request 추가 로직 axios.interceptors.request.use((config) => { return config }) // response 추가 로직 axios.interceptors.request.use(undefined, (error) => {}) const get = async ({ url, option = {} }) => { return await getInstances(url) .get(url, option) .then((res) => res.data) .catch(console.error) } const promiseGet = async ({ url, option = {} }) => { return await getInstances(url).get(url, option) } const post = async ({ url, data, option = {} }) => { return await getInstances(url) .post(url, data, option) .then((res) => res.data) .catch(console.error) } const promisePost = async ({ url, data, option = {} }) => { return await getInstances(url).post(url, data, option) } const put = async ({ url, data, option = {} }) => { return await getInstances(url) .put(url, data, option) .then((res) => res.data) .catch(console.error) } const promisePut = async ({ url, data, option = {} }) => { return await getInstances(url).put(url, data, option) } const patch = async ({ url, data, option = {} }) => { return await getInstances(url) .patch(url, data, option) .then((res) => res.data) .catch(console.error) } const promisePatch = async ({ url, data, option = {} }) => { return await getInstances(url).patch(url, data, option) } const del = async ({ url, option = {} }) => { return await getInstances(url) .delete(url, option) .then((res) => res.data) .catch(console.error) } const promiseDel = async ({ url, option = {} }) => { return await getInstances(url).delete(url, option) } const getFetcher = async (url) => { const res = await get({ url }) return res } const postFetcher = async (url, arg) => { const res = await post({ url, data: arg }) return res } return { get, promiseGet, post, promisePost, put, promisePut, patch, promisePatch, del, promiseDel, getFetcher, postFetcher } }