all files / app/utils/ cookie.ts

24% Statements 6/25
0% Branches 0/14
20% Functions 1/5
20.83% Lines 5/24
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            1× 1×                                                         1×       1×           1×
/* Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 */
 
export class Cookie {
    public static setCookie(name, value, options) {
        options = options || {};
 
        let expires = options.expires;
 
        if (typeof expires === 'number' && expires) {
            let d = new Date();
            d.setTime(d.getTime() + expires * 1000);
            expires = options.expires = d;
        }
        if (expires && expires.toUTCString) {
            options.expires = expires.toUTCString();
        }
 
        value = encodeURIComponent(value);
 
        let updatedCookie = name + '=' + value;
 
        for (let propName in options) {
            updatedCookie += '; ' + propName;
            let propValue = options[propName];
            if (propValue !== true) {
                updatedCookie += '=' + propValue;
            }
        }
 
        document.cookie = updatedCookie;
    }
 
    public static deleteCookie(name) {
        Cookie.setCookie(name, '', {expires: -1});
    }
 
    public static getCookie(name) {
        let matches = document.cookie.match(new RegExp(
            '(?:^|; )' + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + '=([^;]*)'
        ));
        return matches ? decodeURIComponent(matches[1]) : '';
    }
}