목표
- AxiosInstance 구성 보일러 플레이트 설명
1. Axios 인스턴스
1-1) 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