Skip to content

Commit

Permalink
feat: fixing interceptor creator to after config is set #857
Browse files Browse the repository at this point in the history
  • Loading branch information
BruceRodrigues committed May 23, 2023
1 parent f028877 commit 0e6d7da
Showing 1 changed file with 24 additions and 20 deletions.
44 changes: 24 additions & 20 deletions packages/data-explorer-ui/src/entity/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,29 @@ import { getURL } from "../../shared/utils";

let axiosInstance: AxiosInstance | null = null;

/**
* Adding response interceptors to axios instances
* @param api - instance of axios that will receive response interceptors
*/
const configureInterceptors = (api: AxiosInstance): void => {
api.interceptors.response.use(
(response: AxiosResponse) => response,
(error: AxiosError) => {
const { config, response } = error;

if (response?.status === HttpStatusCode.ServiceUnavailable && config) {
const retryAfterValue = response.headers["Retry-After"];
const waitingTime = retryAfterValue ? +retryAfterValue : 0;
return new Promise((resolve) => {
setTimeout(() => resolve(api(config)), waitingTime);
});
}

Promise.reject(error);
}
);
};

/**
* Returns an AxiosInstance to be used to make API calls with a timeout of 10 seconds
* @returns {AxiosInstance} with the current configs URL as baseURL
Expand All @@ -18,26 +41,7 @@ export const api = (): AxiosInstance => {
baseURL: getURL(),
timeout: 10 * 1000,
});
configureInterceptors(axiosInstance);
}
return axiosInstance;
};

/**
* Adding interceptors to axios responses
*/
api().interceptors.response.use(
(response: AxiosResponse) => response,
(error: AxiosError) => {
const { config, response } = error;

if (response?.status === HttpStatusCode.ServiceUnavailable && config) {
const retryAfterValue = response.headers["Retry-After"];
const waitingTime = retryAfterValue ? +retryAfterValue : 0;
return new Promise((resolve) => {
setTimeout(() => resolve(api()(config)), waitingTime);
});
}

Promise.reject(error);
}
);

0 comments on commit 0e6d7da

Please sign in to comment.