/**
* Retries query string operations with basic input validation.
* @param {object} options - Configuration options.
* @param {string} options.url - The URL to perform the operation on.
* @param {function} options.operation - The function to execute with the query string.
* @param {number} options.maxRetries - The maximum number of retries.
* @param {number} options.retryDelay - The delay between retries in milliseconds.
* @param {function} options.validateInput - Function to validate input parameters.
* @returns {Promise} - A promise that resolves with the result of the operation or rejects if all retries fail.
*/
async function retryQueryStringOperation(options) {
const {
url,
operation,
maxRetries = 3,
retryDelay = 1000,
validateInput
} = options;
let retries = 0;
while (retries < maxRetries) {
try {
// Validate input parameters if provided
if (validateInput) {
const params = new URLSearchParams(url.split('?')[1]);
if (!validateInput(params)) {
throw new Error("Invalid query string parameters.");
}
}
// Execute the operation
const result = await operation(url);
return result; // Resolve the promise if successful
} catch (error) {
retries++;
console.log(`Retry attempt ${retries}/${maxRetries} failed: ${error.message}`);
if (retries < maxRetries) {
await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
} else {
throw error; // Re-throw the error if all retries fail
}
}
}
throw new Error(`Max retries (${maxRetries}) reached. Operation failed.`); //Should not reach here if validation is done correctly.
}
Add your comment