|
/** |
|
* @typedef {Object} cookieOptions |
|
* @property {Date} expires - optional |
|
* @property {boolean} secure - optional |
|
* @property {'None' | 'Lax' | 'Strict'} sameSite - optional |
|
* @property {string} path - optional |
|
* @property {string} domain - optional |
|
* @property {boolean} httpOnly - optional |
|
*/ |
|
|
|
/** |
|
* |
|
* @param name {string} |
|
* @param value {string | number | boolean} |
|
* @param options {cookieOptions} |
|
* @returns {string} |
|
*/ |
|
function setCookie (name, value, options = {}) { |
|
if (typeof name !== 'string' || name.length === 0) { |
|
throw new Error("'setCookie' should receive a valid cookie name") |
|
} |
|
|
|
if (!['string', 'number', 'boolean'].includes(typeof value) || value.toString().length === 0) { |
|
throw new Error("'setCookie' should receive a valid cookie value") |
|
} |
|
|
|
/** @type {string[]} */ |
|
const cookieOptions = [`${name}=${value}`] |
|
|
|
if (options?.expires && options?.expires instanceof Date) { |
|
cookieOptions.push(`expires=` + options.expires.toGMTString()) |
|
} |
|
|
|
if (options?.sameSite && typeof options?.sameSite === 'string') { |
|
cookieOptions.push(`SameSite=${options?.sameSite}`) |
|
} |
|
|
|
if (options?.path && typeof options.path === 'string') { |
|
cookieOptions.push(`path=${options?.path}`) |
|
} |
|
|
|
if (options?.domain && typeof options.domain === 'string') { |
|
cookieOptions.push(`domain=${options?.path}`) |
|
} |
|
|
|
if (options?.httpOnly && typeof options.httpOnly === 'boolean') { |
|
cookieOptions.push(`HttpOnly`) |
|
} |
|
|
|
if (options?.secure && typeof options.secure === 'boolean') { |
|
cookieOptions.push('Secure') |
|
} |
|
|
|
const _buildCookie = cookieOptions.join('; ') |
|
|
|
document.cookie = _buildCookie |
|
|
|
return _buildCookie |
|
} |