class ResourceSync {
constructor(formEndpoints, rateLimitMs = 1000) {
this.formEndpoints = formEndpoints; // Array of form endpoint URLs
this.rateLimit = rateLimitMs; // Rate limit in milliseconds
this.lastRun = 0; // Timestamp of the last successful run
}
syncForms() {
const now = Date.now();
if (now - this.lastRun < this.rateLimit) {
console.log("Rate limit exceeded. Waiting...");
setTimeout(() => this.syncForms(), this.rateLimit - (now - this.lastRun)); //Retry after remaining time
return;
}
this.lastRun = now;
for (const endpoint of this.formEndpoints) {
this.syncForm(endpoint);
}
}
async syncForm(endpoint) {
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json(); // Assuming JSON response
// Process the data here. Replace with your actual logic
console.log(`Successfully synced form from ${endpoint}:`, data);
} catch (error) {
console.error(`Error syncing form from ${endpoint}:`, error);
}
}
// Optionally, add a method to schedule the sync
scheduleSync(intervalMs) {
setInterval(this.syncForms, intervalMs);
}
}
// Example Usage:
// const formSync = new ResourceSync([
// "https://example.com/form1",
// "https://example.com/form2",
// "https://example.com/form3"
// ], 5000); // Rate limit of 5 seconds
// formSync.scheduleSync(60000); // Run every minute
Add your comment