All files / src/storage cookie.ts

100% Statements 14/14
100% Branches 3/3
100% Functions 3/3
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44      21x               6x 6x 6x 6x                 5x 5x   5x 2x 2x   3x               2x 2x 2x      
/**
 * Class to handle cookies
 */
export class Cookie {
	/**
	 * Set a cookie
	 * @param name Cookie name
	 * @param value Cookie value
	 * @param expiresAt Expiration date in miliseconds
	 */
	public static setCookie(name: string, value: string, expiresAt?: number): void {
		const date = new Date();
		const expire = expiresAt || 7 * 24 * 60 * 60 * 1000;
		date.setTime(date.getTime() + expire);
		document.cookie = `${name}=${value}; expires=${date.toUTCString()}; path=/`;
	}
 
	/**
	 * Retrieve a cookie value
	 * @param name Cookie name
	 * @returns Cookie value or undefined
	 */
	public static getCookie(name: string): string | undefined {
		const value = `; ${document.cookie}`;
		const parts = value.split(`; ${name}=`);
 
		if (parts.length === 2) {
			const lastElement: string = parts.pop() as string;
			return lastElement.split(';').shift();
		}
		return undefined;
	}
 
	/**
	 * Invalidate a cookie
	 * @param name Cookie name
	 */
	public static deleteCookie(name: string): void {
		const date = new Date();
		date.setTime(date.getTime() + -1 * 24 * 60 * 60 * 1000);
		document.cookie = `${name}=; expires=${date.toUTCString()}; path=/`;
	}
}