Skip to content

Instantly share code, notes, and snippets.

@edmondburnett
Last active July 12, 2023 14:23
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save edmondburnett/38ed3451de659dc43fa3f24befc0073b to your computer and use it in GitHub Desktop.
Save edmondburnett/38ed3451de659dc43fa3f24befc0073b to your computer and use it in GitHub Desktop.
Axios Interceptor to delay and retry original request for certain status code (polling)
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://localhost:5000'
});
const sleepRequest = (milliseconds, originalRequest) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(instance(originalRequest)), milliseconds);
});
};
instance.interceptors.response.use(response => {
return response;
}, error => {
const { config, response: { status }} = error;
const originalRequest = config;
if (status === 420) {
return sleepRequest(1000, originalRequest);
} else {
return Promise.reject(error);
}
});
export default instance;
@iconag-bbasmer
Copy link

iconag-bbasmer commented Jul 12, 2023

How would I use this in the response branch rather than in the error branch? If I check the response for a status like 202 und use the seelRequest function it gives me an Error that the response can't be a Promise or so. I've tried it like this but it does not work, seems to run forever. Any idea?
axiosInstance.interceptors.response.use(
(response) => {
if (
response.status === 202 &&
response.data.pending &&
retryCounter > 0
) {
const { config } = response;
const originalConfig = config;
const waitTime = response.headers['x-retry-after'] * 1000 || 1000;
return new Promise((resolve) => {
const reqTimeOut = setTimeout(() => {
setRetryCounter((ctr) => ctr - 1);
axiosInstance.request(originalConfig).then(resolve);
}, waitTime);
clearTimeout(reqTimeOut);
});
}
return response;
},
(error) => {
return Promise.reject(error);
}
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment