Last active
November 7, 2019 20:56
-
-
Save guilhermebkel/e2612c091b28eb086949a53c474c698e to your computer and use it in GitHub Desktop.
axios-rate-limiter
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 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