Last active
May 7, 2022 05:12
-
-
Save ccheney/957481d88a5060ab4bb3401cdee296ac to your computer and use it in GitHub Desktop.
axios http interceptor with minimum delayed response
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
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