1. class RequestThrottler {
  2. constructor(maxRequestsPerSecond) {
  3. this.maxRequestsPerSecond = maxRequestsPerSecond;
  4. this.requestQueue = [];
  5. this.lastRequestTime = 0;
  6. }
  7. /**
  8. * Throttles a request to prevent overwhelming the system.
  9. * @param {function} requestFunction The function to execute (the actual request).
  10. * @param {object} data The data to send with the request.
  11. * @returns {Promise} A promise that resolves when the request is complete.
  12. * @throws {Error} If the data is invalid.
  13. */
  14. throttle(requestFunction, data) {
  15. // Input validation
  16. if (!data || typeof data !== 'object') {
  17. throw new Error("Invalid data: Data must be an object.");
  18. }
  19. if (typeof requestFunction !== 'function') {
  20. throw new Error("Invalid requestFunction: requestFunction must be a function.");
  21. }
  22. return new Promise((resolve, reject) => {
  23. const now = Date.now();
  24. const timeSinceLastRequest = now - this.lastRequestTime;
  25. if (timeSinceLastRequest < 1000 / this.maxRequestsPerSecond) {
  26. // Queue the request if it's too frequent.
  27. this.requestQueue.push({ function: requestFunction, data: data });
  28. } else {
  29. // Execute the request immediately.
  30. this.lastRequestTime = now;
  31. requestFunction(data, resolve, reject); // Pass resolve and reject to the function.
  32. }
  33. });
  34. }
  35. /**
  36. * Processes the request queue.
  37. */
  38. processQueue() {
  39. while (this.requestQueue.length > 0) {
  40. const { function: requestFunction, data: data } = this.requestQueue.shift();
  41. this.throttle(requestFunction, data)
  42. .then(() => {
  43. // Request completed successfully.
  44. })
  45. .catch(error => {
  46. // Request failed.
  47. console.error("Request failed:", error);
  48. // Optionally, handle the error (e.g., retry, log).
  49. });
  50. }
  51. }
  52. }
  53. // Example usage:
  54. // const throttler = new RequestThrottler(5); // Allow 5 requests per second
  55. // async function fetchData(data, resolve, reject) {
  56. // console.log("Fetching data:", data);
  57. // await new Promise(resolve => setTimeout(resolve, 200)); // Simulate network request
  58. // resolve({ message: "Data fetched successfully" });
  59. // }
  60. // try {
  61. // await throttler.throttle(fetchData, { userId: 123 });
  62. // console.log("Request completed.");
  63. // } catch (error) {
  64. // console.error("Error:", error);
  65. // }

Add your comment