/**
* Sets session cookies for short-lived tasks with sanity checks.
* @param {object} options - Configuration options for the session.
* @param {string} options.domain - The domain for the cookies.
* @param {string} options.path - The path for the cookies.
* @param {number} options.expires - The expiration time in milliseconds.
* @param {boolean} options.secure - Whether the cookie should be secure.
* @param {boolean} options.httpOnly - Whether the cookie should be HTTPOnly.
* @param {object} options.data - An object containing the cookie data.
* @returns {Promise<void>}
*/
async function setSessionCookie(options) {
try {
const { domain, path, expires, secure, httpOnly, data } = options;
if (!domain || !path || expires <= 0) {
throw new Error("Domain, path, and expires must be provided.");
}
const cookie = {
name: 'session_id', // Example cookie name
value: data.id, // Example cookie data
domain: domain,
path: path,
expires: new Date(expires), // Convert milliseconds to Date object
secure: secure,
httpOnly: httpOnly,
};
// Sanity check: Ensure expires is a valid date
if (isNaN(cookie.expires.getTime())) {
throw new Error("Invalid expires value. Must be a valid date in milliseconds.");
}
document.cookie = `${cookie.name}=${cookie.value}; ${cookie.domain}; ${cookie.path}; ${cookie.expires}; ${cookie.secure}; ${cookie.httpOnly}`;
console.log("Session cookie set successfully.");
} catch (error) {
console.error("Error setting session cookie:", error.message);
throw error; // Re-throw the error for handling upstream
}
}
Add your comment