Implementing rate limiting #205
Replies: 2 comments
-
@RProduction I think the middleware can help you. this is my thought about your problem. I code a middleware function to show my thought but it has not been tested, you can refer to it. const createRateLimitMiddleware = ({ maxRequests, perMilliseconds }) => {
let timer, waitingList = [], requestingCount = 0;
const run = () => {
if (requestingCount >= maxRequests) {
return;
}
const resolveFn = waitingList.unshift();
if (!resolveFn && timer) {
clearInterval(timer);
timer = undefined;
}
resolveFn();
run(); // continue to check and run request
}
return async (ctx, next) => {
// create a promise instance to delay request when reached maxRequests
const p = new Promise(resolve => {
waitingList.push(resolve);
});
if (!timer) {
run();
// after reached maxRequests, if has waiting promises in waitingList, it will set an interval to resolve them.
if (waitingList.length > 0) {
timer = setInterval(run, perMilliseconds);
}
}
await p;
requestingCount++;
await next();
requestingCount--;
};
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
Wow I appreciate the help. Let me test it if I have time. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello I need help to implement rate limit when using alova.
First, I am using alova for fetching data inside recoiljs(state management lib). So I have 2 options, to implement rate limiting using alova or the state. But I don't think there is a way to delay fetching of state management so I decided to implement it in alova.
I am using send method, so maybe middleware can't help.
I don't have any idea how to implement it, but I see there is a library for rate limiting in axios and I am using axios adapter for alova.
https://www.npmjs.com/package/axios-rate-limit
Anyone, any good idea for this?
Beta Was this translation helpful? Give feedback.
All reactions