import { navigator } from "./browser-utils"; import { DomainUtils } from "./domain-utils"; /** * Cookie Utils. * * @export * @abstract * @class CookieUtils */ export abstract class CookieUtils { public static enabled: boolean = navigator()?.cookieEnabled || false; /** * Set a value as a cookie. * * @static * @param {string} name Cookie's name. * @param {string} value Cookie's value. * @param {CookieOptions} [options={}] Options * @memberof CookieUtils */ public static set(name: string, value: string, options: CookieOptions = {}): void { let cookie = `${name}=${value}`; if (options.domain) { cookie += `;domain=${options.domain}`; } if (options.ttl) { const expires = new Date(new Date().getTime() + options.ttl * 1000); cookie += `;expires=${expires.toUTCString()}`; } if (options.path) { cookie += `;path=${options.path}`; } else { cookie += ";path=/"; } document.cookie = cookie; } /** * Get a value from a cookie. * * @static * @param {string} name Cookie's name. * @return {string | undefined} Cookie's value or undefined. * @memberof CookieUtils */ public static get(name: string): string | undefined { const groups = new RegExp(`${name}=([^\\s;]*)`).exec(document.cookie); if (groups && groups[1]) { return groups[1]; } return undefined; } /** * Extrai o domínio raiz da url * * @static * @return {string} Domínio raiz da url * @memberof CookieUtils */ public static getDomain(): string { const urlParts = document.domain.split(".").reverse(); let newParts = []; let locationResult = ""; for (const p of urlParts) { newParts.push(p); if (!DomainUtils.isTLD(p)) { break; } } newParts = newParts.reverse(); for (const n of newParts) { locationResult += n; if (n !== newParts[newParts.length - 1]) { locationResult += "."; } } return locationResult; } } /** * Options to create a cookie * * @export * @interface CookieOptions */ export interface CookieOptions { domain?: string; ttl?: number; path?: string; }