1. /**
  2. * Guards cookie execution for scheduled runs with graceful failure handling.
  3. *
  4. * @param {Function} task The function to execute with cookie access.
  5. * @param {object} options Configuration options.
  6. * @param {string} options.cookieName The name of the cookie to access.
  7. * @param {string} options.cookiePath The path of the cookie.
  8. * @param {number} options.timeout The timeout for cookie retrieval (in milliseconds).
  9. * @param {number} [options.retries=3] The number of retries if cookie retrieval fails.
  10. */
  11. function guardedCookieExecution(task, options = {}) {
  12. const { cookieName, cookiePath, timeout, retries = 3 } = options;
  13. async function executeTask() {
  14. let attempts = 0;
  15. while (attempts < retries) {
  16. try {
  17. const cookieValue = document.cookie.split('; ').find(
  18. (cookie) => cookie.startsWith(`${cookieName}=`)
  19. );
  20. if (cookieValue) {
  21. // Cookie found, execute the task
  22. await task(cookieValue);
  23. return; // Exit after successful execution
  24. } else {
  25. // Cookie not found, retry if within timeout
  26. attempts++;
  27. await new Promise((resolve) => setTimeout(resolve, timeout));
  28. }
  29. } catch (error) {
  30. // Handle potential errors during cookie retrieval or task execution
  31. attempts++;
  32. await new Promise((resolve) => setTimeout(resolve, timeout));
  33. }
  34. }
  35. // Task failed after multiple retries
  36. console.error(`Task failed after ${retries} retries. Cookie "${cookieName}" not found.`);
  37. throw new Error(`Task failed: Cookie "${cookieName}" not found after multiple attempts.`);
  38. }
  39. executeTask();
  40. }

Add your comment