Axios Requst 구조

Potato·2023년 6월 16일

TIL

목록 보기
8/10

기존 사용하던 Axios

Axios를 사용할때 최근까지 간단한 Axios Instance 정도 만들어놓고 commonApi/authApi... 안에

import instance from '@/utils/axiosInstance';
import type { AxiosRequestConfig } from 'axios';

export class Api {
  static get = async <T = any>(url: string, config?: AxiosRequestConfig) => {
    try {
      const response = await instance.get<T>(url, { ...config });
      return response.data;
    } catch (error) {
      throw error;
    }
  };

  static post = async <T = any>(
    url: string,
    body?: any,
    config?: AxiosRequestConfig
  ) => {
    try {
      const response = await instance.post<T>(url, body, {
        ...config,
      });
      return response.data;
    } catch (error) {
      throw error;
    }
  };

  static put = async <T = any>(
    url: string,
    body?: any,
    config?: AxiosRequestConfig
  ) => {
    try {
      const response = await instance.put<T>(url, body, { ...config });
      return response.data;
    } catch (error) {
      throw error;
    }
  };

  static patch = async <T = any>(
    url: string,
    body?: any,
    config?: AxiosRequestConfig
  ) => {
    try {
      const response = await instance.patch<T>(url, body, { ...config });
      return response.data;
    } catch (error) {
      throw error;
    }
  };

  static delete = async <T = any>(url: string, config?: AxiosRequestConfig) => {
    try {
      const response = await instance.delete<T>(url, { ...config });
      return response.data;
    } catch (error) {
      throw error;
    }
  };
}


// 사용
const result = await Api.post('users/reset/pw', userInfo);

Class 형식으로 각 Http 요청에 대한 static 함수를 적용해서 만들곤 했는데
팀 프로젝트에서 새로운 팀원분이 Axios 코드를 만든 구조가 좋아보였다.

새로운 팀에서 사용하는 Axios 구조

Axios Instance 생성

기존과 동일하게 Axios Instance는 생성해준다.

import axios, { AxiosRequestConfig } from 'axios'
import { BASE_URL } from "@env"
const config: AxiosRequestConfig = {
  baseURL: BASE_URL,
}
export const OurServer = axios.create(config)

requestData constant 생성

/* eslint-disable no-useless-catch */
import axios, { AxiosResponse } from 'axios'
import { Alert } from 'react-native'
import { BOBServer } from './baseURL'
type Method = 'post' | 'get' | 'delete' | 'put' | 'patch'
type RequestFuncType = <T, U>(url: string, method: Method, params?: T, body?: U) => Promise<AxiosResponse>

export const requestData: RequestFuncType = async (url, method, params, body) => {
  const SERVER_ERROR = 'There was an error contacting the server.'
  try {
    const res = await BOBServer.request({ url, method, params, data: body })
    console.log(res)
    if (res.status >= 200 && res.status < 300) {
      return res
    } else {
      throw { res }
    }
  } catch (error) {
    const msg =
      axios.isAxiosError(error) && error?.response?.data?.message ? error?.response?.data?.message : SERVER_ERROR
    Alert.alert(msg)
    throw { data: null, msg }
  }
}

이렇게 해두면 try catch 문에서의 error 가 SERVER_ERROR 혹은 서버에서 주는 에러를 { msg }에서 뽑아서 사용할 수 있게된다.

xxxRequests.ts 작성

/* eslint-disable no-useless-catch */
import { AxiosResponse } from 'axios'
import { requestData } from './constansts'
export const authRequest = {
  userLogin: async (loginData: { id: string; password: string }) => {
    const { data } = await requestData('/auth/login', 'post', loginData)
    return data
  },
  userSignUp: async (userData: {
    id: string
    password: string
    phone: string
    name: string
    nickname: string
    gender: 'Male' | 'Female'
    age: number
  }) => {
    const { data } = await requestData('/auth/login', 'post', userData)
    return data
  },
  userLogout: async () => {
    const { data } = await requestData('/auth/logout', 'post')
    return data
  },
  userSMS: async (phone: string) => {
    const { data } = await requestData('/auth/sms', 'post', { phone })
    return data
  },
  userVerificationCode: async (phone: string, token: string) => {
    const { data } = await requestData('/auth/sms/check', 'post', { phone, token })
    return data
  },
}

0개의 댓글