axios interceptor에서 중복된 http 요청 막기

YUKI KIM·2022년 10월 5일
3

유저가 서비스 내에서 무언가를 submit할 때, 실수든 고의든 서버에 중복된 요청을 보내게 된다면 서버에 불필요한 요청을 보내게 되며 + 유저 경험도 낮아진다. 따라서 중복된 요청이라면 프론트에서 api 요청을 자체적으로 취소시키는 법을 알아봤다.


interceptors 안에서 Key 관리

우선 중복된 요청인지 아닌지 알아야된다. 이를 위해선, 요청을 보낼 때마다 key값을 저장해준다.

instance.interceptors.request.use(
  (config: AxiosRequestConfig) => config,
  (err: AxiosError) => Promise.reject(err),
);

위는 일반적인 axios의 request interceptor이다. config를 사용하면 해당 요청의 url, method, data 등을 알 수 있는데 이 값들을 잘 조합해서 Key로 만들어준다.

나의 경우 Key를 ${config.url}$${JSON.stringify(config.data)}로 지정했다. 그리고 store용 객체에 이 Key를 저장해준다. 그럼 객체는 아래와 같은 모습을 한다.

{
  `${config.url}$${JSON.stringify(config.data)}`: TimeStamp,
  `${config.url}$${JSON.stringify(config.data)}`: TimeStamp,
  ...
}

중복된 요청 취소하기

이제 중복된 Key라면, 요청을 취소해줄거다. Key를 요청마다 store용 객체에 검색하여 있다면, request를 취소시키고, 없다면, Key를 객체에 저장하고 그대로 요청을 보내면 된다.

이를 코드로 나타내면 아래와 같다.

// Store requests
const sourceRequest: any = {};

instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (config.method === 'post') {
      const key = `${config.url}$${JSON.stringify(config.data)}`;

      if (sourceRequest[key]) {
        throw new Error('Automatic cancellation'); // If the request exists cancel
      } else {
        sourceRequest[key] = new Date(); // Store request key
      }
    }
    return config;
  },
);



레퍼런스

profile
유키링と 욘데 쿠다사이

0개의 댓글