/**
* Guards cookie execution for scheduled runs with graceful failure handling.
*
* @param {Function} task The function to execute with cookie access.
* @param {object} options Configuration options.
* @param {string} options.cookieName The name of the cookie to access.
* @param {string} options.cookiePath The path of the cookie.
* @param {number} options.timeout The timeout for cookie retrieval (in milliseconds).
* @param {number} [options.retries=3] The number of retries if cookie retrieval fails.
*/
function guardedCookieExecution(task, options = {}) {
const { cookieName, cookiePath, timeout, retries = 3 } = options;
async function executeTask() {
let attempts = 0;
while (attempts < retries) {
try {
const cookieValue = document.cookie.split('; ').find(
(cookie) => cookie.startsWith(`${cookieName}=`)
);
if (cookieValue) {
// Cookie found, execute the task
await task(cookieValue);
return; // Exit after successful execution
} else {
// Cookie not found, retry if within timeout
attempts++;
await new Promise((resolve) => setTimeout(resolve, timeout));
}
} catch (error) {
// Handle potential errors during cookie retrieval or task execution
attempts++;
await new Promise((resolve) => setTimeout(resolve, timeout));
}
}
// Task failed after multiple retries
console.error(`Task failed after ${retries} retries. Cookie "${cookieName}" not found.`);
throw new Error(`Task failed: Cookie "${cookieName}" not found after multiple attempts.`);
}
executeTask();
}
Add your comment