API 모듈화 하기

뱀기·2023년 3월 19일
0

리팩토링

목록 보기
8/8

API의 가독성을 높이기 위해 모듈화를 진행했다.

axios 인스턴스

인스턴스 생성

axios.create([config])로 axios 인스턴스를 생성한다.

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
...

utill 생성

api 요청 utill을 만듬.
token을 필요로 하는 경우 token을 받고 아닌 경우는 생략함.


export const requestWithAuth = async ({ ...options }, token) => {
  instance.defaults.headers.common.Authorization = `Bearer ${token}`;
  instance.defaults.headers.common['Content-Type'] = 'application/json';

  const onSuccess = (res) => res?.data;
  const onError = (err) => {
    throw err;
  };

  return await instance(options).then(onSuccess).catch(onError);
};

export const requestWithoutAuth = async ({ ...options }) => {
  delete instance.defaults.headers.common.Authorization;
  instance.defaults.headers.common['Content-Type'] = 'application/json';
  
  const onSuccess = (res) => res?.data;
  const onError = (err) => {
    throw err;
  };

  return await instance(options).then(onSuccess).catch(onError);
};

utill 사용

좀 더 가독성 높은 코드를 작성할 수 있었다.
method, url, data, content-type 등 필요한 옵션을 사용하여 request util을 사용한다.

export const requestApi = async (data) => {
  return await requestWithAuth({
    method: 'post',
    url: URL,
    data,
    'Content-Type': 'multipart/form-data',
  });
};

코드의 가독성을 높이기 위해 한 작업으로 코드량도 상당하게 줄일 수 있었다.
좋은 작업이었다...!

0개의 댓글