1. class ResourceSync {
  2. constructor(formEndpoints, rateLimitMs = 1000) {
  3. this.formEndpoints = formEndpoints; // Array of form endpoint URLs
  4. this.rateLimit = rateLimitMs; // Rate limit in milliseconds
  5. this.lastRun = 0; // Timestamp of the last successful run
  6. }
  7. syncForms() {
  8. const now = Date.now();
  9. if (now - this.lastRun < this.rateLimit) {
  10. console.log("Rate limit exceeded. Waiting...");
  11. setTimeout(() => this.syncForms(), this.rateLimit - (now - this.lastRun)); //Retry after remaining time
  12. return;
  13. }
  14. this.lastRun = now;
  15. for (const endpoint of this.formEndpoints) {
  16. this.syncForm(endpoint);
  17. }
  18. }
  19. async syncForm(endpoint) {
  20. try {
  21. const response = await fetch(endpoint);
  22. if (!response.ok) {
  23. throw new Error(`HTTP error! Status: ${response.status}`);
  24. }
  25. const data = await response.json(); // Assuming JSON response
  26. // Process the data here. Replace with your actual logic
  27. console.log(`Successfully synced form from ${endpoint}:`, data);
  28. } catch (error) {
  29. console.error(`Error syncing form from ${endpoint}:`, error);
  30. }
  31. }
  32. // Optionally, add a method to schedule the sync
  33. scheduleSync(intervalMs) {
  34. setInterval(this.syncForms, intervalMs);
  35. }
  36. }
  37. // Example Usage:
  38. // const formSync = new ResourceSync([
  39. // "https://example.com/form1",
  40. // "https://example.com/form2",
  41. // "https://example.com/form3"
  42. // ], 5000); // Rate limit of 5 seconds
  43. // formSync.scheduleSync(60000); // Run every minute

Add your comment