summaryrefslogtreecommitdiff
path: root/shared/components/src/utils/cookie.ts
blob: 112733f21e376411d988f82befd49d873033266b (plain)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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;
}