diff options
| author | rxliuli <rxliuli@gmail.com> | 2025-11-04 05:03:50 +0800 |
|---|---|---|
| committer | rxliuli <rxliuli@gmail.com> | 2025-11-04 05:03:50 +0800 |
| commit | bce557cc2dc767628bed6aac87301a1be7c5431b (patch) | |
| tree | b51a051228d01fe3306cd7626d4a96768aadb944 /shared/components/src/utils/cookie.ts | |
init commit
Diffstat (limited to 'shared/components/src/utils/cookie.ts')
| -rw-r--r-- | shared/components/src/utils/cookie.ts | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/shared/components/src/utils/cookie.ts b/shared/components/src/utils/cookie.ts new file mode 100644 index 0000000..112733f --- /dev/null +++ b/shared/components/src/utils/cookie.ts @@ -0,0 +1,71 @@ +export function getCookie(name: string): string | null { + if (typeof document === 'undefined') { + return null; + } + + const prefix = `${name}=`; + const cookie = document.cookie + .split(';') + .map((value) => value.trimStart()) + .filter((value) => value.startsWith(prefix))[0]; + + if (!cookie) { + return null; + } + + return cookie.substr(prefix.length); +} + +export function setCookie( + name: string, + value: string, + domain: string, + expires = 0, + path = '/', +): void { + if (typeof document === 'undefined') { + return undefined; + } + + // Get any potential existing instances of this particular cookie + const existingCookie = getCookie(name); + let cookieValue = value; + + if (existingCookie) { + // If exisitng cookie name does not include the value we are trying to set, + // then add it, otherwise use the existing cookie value + cookieValue = !existingCookie.includes(value) + ? `${existingCookie}+${value}` + : existingCookie; + } + + let cookieString = `${name}=${cookieValue}; path=${path}; domain=${domain};`; + + if (expires) { + const date = new Date(); + date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000); + + cookieString += ` expires=${date.toUTCString()};`; + } + + document.cookie = cookieString; + + // Returning undefined because of ESLint's "consistent-return" rule + return undefined; +} + +export function clearCookie(name: string, domain: string, path = '/'): void { + if (typeof document === 'undefined') { + return undefined; + } + + // Get any potential existing instances of this particular cookie + const existingCookie = getCookie(name); + + if (existingCookie) { + // Set the cookie's expiration date to a past date + setCookie(name, '', domain, -1, path); + } + + return undefined; +} |
