1. /**
  2. * Extends existing dataset logic with rate limiting.
  3. *
  4. * @param {function} originalFunction The original function to be rate limited.
  5. * @param {number} maxRequestsPerSecond The maximum number of requests allowed per second.
  6. * @returns {function} A rate-limited version of the original function.
  7. */
  8. function rateLimit(originalFunction, maxRequestsPerSecond) {
  9. let queue = []; // Queue to hold requests
  10. let running = 0; // Number of currently executing requests
  11. let lastExecutionTime = 0; // Time of the last execution
  12. /**
  13. * Rate-limited version of the original function.
  14. * @param {...any} args Arguments to pass to the original function.
  15. * @returns {Promise<any>} A promise that resolves with the result of the original function.
  16. */
  17. return async function (...args) {
  18. return new Promise((resolve, reject) => {
  19. const now = Date.now();
  20. // Check if we're exceeding the rate limit
  21. if (running >= maxRequestsPerSecond) {
  22. // Add the request to the queue
  23. queue.push({ args, resolve, reject });
  24. return;
  25. }
  26. // Start the request
  27. running++;
  28. const startTime = now;
  29. // Execute the original function
  30. originalFunction(...args)
  31. .then(result => {
  32. // Resolve the promise with the result
  33. resolve(result);
  34. })
  35. .catch(error => {
  36. // Reject the promise with the error
  37. reject(error);
  38. })
  39. .finally(() => {
  40. // Decrement the number of running requests
  41. running--;
  42. // Process the queue
  43. processQueue();
  44. });
  45. });
  46. };
  47. /**
  48. * Processes the request queue.
  49. */
  50. function processQueue() {
  51. while (queue.length > 0) {
  52. const { args, resolve, reject } = queue.shift();
  53. const now = Date.now();
  54. // Check if the rate limit has been exceeded
  55. if (now - lastExecutionTime >= 1000) {
  56. // Reset the rate limit
  57. running = 0;
  58. lastExecutionTime = now;
  59. }
  60. }
  61. }
  62. }

Add your comment