Last active
July 12, 2023 14:23
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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);
}
);