Axios 인스턴스 구성 예제

이춘길·2021년 11월 20일
1
post-thumbnail
post-custom-banner

목표

  • AxiosInstance 구성 보일러 플레이트 설명

1. Axios 인스턴스

1-1) Axios 추상 클래스 생성

  • axios 인스턴스 생성
import axios, { AxiosInstance } from 'axios';

abstract class HttpClient {
  protected readonly instance: AxiosInstance;

  public constructor(baseURL: string) {
    this.instance = axios.create({
      baseURL,
    });
  }
}

1-2) Response Interceptor 구현

  • AxiosResponse 재정의
  • Response Intercepor 정의
import axios, { AxiosInstance, AxiosResponse } from 'axios';

declare module 'axios' {
  interface AxiosResponse<T = any> extends Promise<T> {}
}

abstract class HttpClient {
  protected readonly instance: AxiosInstance;
  
  public constructor(baseURL: string) {
    this.instance = axios.create({
      baseURL,
    });

    this._initializeResponseInterceptor();
  }

  private _initializeResponseInterceptor = () => {
    this.instance.interceptors.response.use(
      this._handleResponse,
      this._handleError,
    );
  };

  private _handleResponse = ({ data }: AxiosResponse) => data;
  protected _handleError = (error: any) => Promise.reject(error);
}

2. 사용 사례

2-1) Authorization이 없는 경우

import HttpClient from './http-client';
import { User } from './types';

const URI_USER:string = '/users';
const URI_USER_ID:string = `${URI_USER}/${id}`

class MainApi extends HttpClient {
  public constructor() {
    super(process.env.REACT_APP_API_DOMAIN);
  }

  public getUsers = () => this.instance.get<User[]>(URI_USER);
  public getUser = (id: string) => this.instance.get<User>(URI_USER_ID);
}

2-2) Authorization이 있는 경우

  • 추상화를 위해 두 사례로 나뉘어서 분리
import { AxiosRequestConfig } from 'axios';
import { CreateUserBody } from './types';

const URI_USER:string = '/users';

class MainApiProtected extends HttpClient {
  public constructor() {
    super(process.env.REACT_APP_API_DOMAIN);
    this._initializeRequestInterceptor();
  }

  private _initializeRequestInterceptor = () => {
    this.instance.interceptors.request.use(
      this._handleRequest,
      this._handleError,
    );
  };

  private _handleRequest = (config: AxiosRequestConfig) => {
    config.headers['Authorization'] = 'Bearer ...';
    return config;
  };

  public createUser = (body: CreateUserBody) => this.instance.post(URI_USER, body);
}

출처

Axios Best Practice

profile
일지를 꾸준히 작성하자.
post-custom-banner

0개의 댓글