Skip to content

Instantly share code, notes, and snippets.

@guilhermebkel
Last active November 7, 2019 20:56
Show Gist options
  • Save guilhermebkel/e2612c091b28eb086949a53c474c698e to your computer and use it in GitHub Desktop.
Save guilhermebkel/e2612c091b28eb086949a53c474c698e to your computer and use it in GitHub Desktop.
axios-rate-limiter
import axios from 'axios'
const CONCURRENT_UPLOADS = 6
// Time between verifications to know if there's
// a space on the queue to make a new request
const INTERVAL_MS = 10
let PENDING_UPLOADS = 0
const upload = axios.create({})
// Intercepts the request and stops it till the
// queue has space enough to make a new one
upload.interceptors.request.use(function (config) {
return new Promise(resolve => {
let interval = setInterval(() => {
if (PENDING_UPLOADS < CONCURRENT_UPLOADS) {
PENDING_UPLOADS++
clearInterval(interval)
resolve(config)
}
}, INTERVAL_MS)
})
})
// Intercepts the response to free up space on the
// queue.
upload.interceptors.response.use(function (response) {
PENDING_UPLOADS = Math.max(0, PENDING_UPLOADS - 1)
return Promise.resolve(response)
}, function (error) {
PENDING_UPLOADS = Math.max(0, PENDING_UPLOADS - 1)
return Promise.reject(error)
})
export default upload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment