Skip to content

Instantly share code, notes, and snippets.

@ccheney
Last active May 7, 2022 05:12
Show Gist options
  • Save ccheney/957481d88a5060ab4bb3401cdee296ac to your computer and use it in GitHub Desktop.
Save ccheney/957481d88a5060ab4bb3401cdee296ac to your computer and use it in GitHub Desktop.
axios http interceptor with minimum delayed response
const httpInterceptor = {
setupInterceptors: () => {
axios.interceptors.request.use((config) => {
return {
...config,
p0: performance.now(),
};
}, (error) => Promise.reject(error));
axios.interceptors.response.use(async (response) => {
const minimumDelay = 500;
const latency = performance.now() - response.config.p0;
const shouldNotDelay = minimumDelay < latency;
if (shouldNotDelay) {
return response;
}
const remainder = minimumDelay - latency;
const [responseWithDelay] = await Promise.all([
response,
new Promise((resolve) => setTimeout(resolve, remainder)),
]);
return responseWithDelay;
}, (error) => Promise.reject(error));
}
};
export default httpInterceptor;
/**
* usage
* wherever you import axios
* httpIntercepter.setupInterceptors():
*
* You could also provide an argument, like
* a redux store. Grab pieces of state, such
* as a token or even call store.dispatch(), etc
*
* httpIntercepter.setupInterceptors(store):
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment