aishek / axios-rate-limit

Rate limit for axios
MIT License
237 stars 35 forks source link

Enable Sharing the AxiosRateLimit instance between AxiosClient instances #75

Open leorochael opened 4 months ago

leorochael commented 4 months ago

Currently the axiosRateLimit function is the only export from the module, but I would like to be able to share rate-limiting between axios clients. That is, I'd like to be able to do something like this:

import axios from 'axios';
import rateLimit, { AxiosRateLimiter } from 'axios-rate-limit'

const limiter = AxiosRateLimiter( { maxRequests: 2, perMilliseconds: 1000, maxRPS: 2 } );

const sheet1 = rateLimit(axios.create({ baseURL: `${SHEETS_API_BASE_URL}/${spreadsheetId1}` }), { rateLimiter: limiter});
const sheet2 = rateLimit(axios.create({ baseURL: `${SHEETS_API_BASE_URL}/${spreadsheetId2}` }), { rateLimiter: limiter}); 

So that both sheet1 and sheet2 are rate-limited as if they were a single rate limited axios client. I.e. if two requests are done in the same second on client1, then a third request in the same second for client2 would be rate-limited into the next second.

From what I can see in the code, it's almost ready for that, as the axios parameter in the constructor for AxiosRateLimit is only used for the .enable() call, and in there it's only used to .use() the interceptors. And though it stores the return values of the .use() calls, it doesn't actually do anything with them.