test

sdfsdf
mail@pastecode.io avatar
unknown
javascript
2 years ago
1.3 kB
1
Indexable
Never
import axios from 'axios';
import { ENV, STATUS_CODES } from '../../config/constants';

const axiosConn = axios.create({
  baseURL: ENV.SFDC_API_DOMAIN,
});

axiosConn.count = 0;

axiosConn.interceptors.request.use(
  (config) => {
    if (conn.accessToken) {
      // eslint-disable-next-line no-param-reassign
      config.headers = {
        Authorization: `Bearer ${conn.accessToken}`,
      };
    }

    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

axiosConn.interceptors.response.use(
  (response) => {
    axiosConn.count = 0;
    return response;
  },
  async (error) => {
    if (error.response.status === 401) {
      try {
        if (axiosConn.count === 3) {
          return Promise.reject(error);
        }

        const { access_token: accessToken } = await conn.oauth2.refreshToken(
          conn.refreshToken,
        );

        // eslint-disable-next-line no-plusplus
        axiosConn.count++;

        const { config } = error;
        config.headers.Authorization = `Bearer ${accessToken}`;
        return await axiosConn.request(config);
      } catch (err) {
        return Promise.reject(err);
      }
    }
    return Promise.reject(error);
  },
);

export default axiosConn;