1. /**
  2. * Retries query string operations with basic input validation.
  3. * @param {object} options - Configuration options.
  4. * @param {string} options.url - The URL to perform the operation on.
  5. * @param {function} options.operation - The function to execute with the query string.
  6. * @param {number} options.maxRetries - The maximum number of retries.
  7. * @param {number} options.retryDelay - The delay between retries in milliseconds.
  8. * @param {function} options.validateInput - Function to validate input parameters.
  9. * @returns {Promise} - A promise that resolves with the result of the operation or rejects if all retries fail.
  10. */
  11. async function retryQueryStringOperation(options) {
  12. const {
  13. url,
  14. operation,
  15. maxRetries = 3,
  16. retryDelay = 1000,
  17. validateInput
  18. } = options;
  19. let retries = 0;
  20. while (retries < maxRetries) {
  21. try {
  22. // Validate input parameters if provided
  23. if (validateInput) {
  24. const params = new URLSearchParams(url.split('?')[1]);
  25. if (!validateInput(params)) {
  26. throw new Error("Invalid query string parameters.");
  27. }
  28. }
  29. // Execute the operation
  30. const result = await operation(url);
  31. return result; // Resolve the promise if successful
  32. } catch (error) {
  33. retries++;
  34. console.log(`Retry attempt ${retries}/${maxRetries} failed: ${error.message}`);
  35. if (retries < maxRetries) {
  36. await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
  37. } else {
  38. throw error; // Re-throw the error if all retries fail
  39. }
  40. }
  41. }
  42. throw new Error(`Max retries (${maxRetries}) reached. Operation failed.`); //Should not reach here if validation is done correctly.
  43. }

Add your comment