/**
* Guards execution of URL lists for backward compatibility with rate limiting.
*
* @param {string[]} urls An array of URLs to execute.
* @param {function} rateLimitFunction A function that checks if rate limiting allows execution.
* Should return true if allowed, false otherwise.
* @param {number} [limit=10] The rate limit.
* @param {number} [interval=1000] The interval between requests (in milliseconds).
* @returns {Promise<void>} A promise that resolves when all URLs have been executed or rejected if rate limiting fails.
* @throws {Error} If urls is not an array or rateLimitFunction is not a function.
*/
async function guardUrlExecution(urls, rateLimitFunction, limit = 10, interval = 1000) {
if (!Array.isArray(urls)) {
throw new Error("urls must be an array.");
}
if (typeof rateLimitFunction !== 'function') {
throw new Error("rateLimitFunction must be a function.");
}
let executedCount = 0;
for (const url of urls) {
if (!rateLimitFunction(executedCount, limit, interval)) {
console.log(`Rate limit exceeded. Skipping URL: ${url}`);
return; // Stop execution if rate limit is exceeded
}
try {
// Simulate URL execution (replace with your actual logic)
await executeUrl(url); // Replace with your URL execution logic
executedCount++;
console.log(`Executed URL: ${url}`);
} catch (error) {
console.error(`Error executing URL ${url}:`, error);
// Handle errors as needed (e.g., retry, log, etc.)
}
}
}
/**
* Simulates executing a URL. Replace with your actual URL execution logic.
* @param {string} url The URL to execute.
* @returns {Promise<void>} A promise that resolves when the URL is executed.
*/
async function executeUrl(url) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 500); // Simulate some work
});
}
Add your comment