Untitled

 avatar
unknown
javascript
2 years ago
1.9 kB
6
Indexable
const showError = (errorStatus, message = '') => {
  Sentry.captureMessage(`Lỗi API Futures: ${message}`);
};

export const createAxios = (config, isPrivate) => {
  const axiosInstance = axios.create({
    ...defaultConfigAxios,
    ...config,
  });

  axiosInstance.interceptors.request.use(req => {
    if (isPrivate) {
      const token = getTokenByStore().access_token;
      req.headers.Authorization = `Bearer ${token}`;
      
    }
    return req;
  });

  axiosInstance.interceptors.response.use(
    response => {
      if (response.status < 200 || response.status > 300) {
        console.log('response error', response);
      }
      return response;
    },
    async error => {
      const errorConfig = error.config;
      const responseError = {
        ...error,
        response: {
          ...error.response,
        },
      };

      if (
        error?.response?.status === 401 &&
        !errorConfig._retry &&
        !isRefreshing
      ) {
        errorConfig._retry = true;
        try {
          const token = getTokenByStore();
          refreshAccessToken(token);
          isRefreshing = isRefreshing
            ? isRefreshing
            : refreshAccessToken(token);
          await isRefreshing;
          isRefreshing = null;
          return axiosInstance(errorConfig);
        } catch (err) {
          return Promise.reject(err);
        }

      } else {
        if (
          error?.response?.status !== 401 &&
          responseError?.response?.config?.url
        ) {
          showError(
            responseError?.response?.data?.code,
            `url: ${responseError?.response?.config?.url}\nstatus: ${responseError?.response?.status}\nmessage: ${responseError?.response?.data?.message}`,
          );
        }
      }
      // console.log('handle error api', responseError?.response?.data?.code);
      return responseError;
    },
  );

  return axiosInstance;
};
Editor is loading...