util_data_cookie_manager.js

/**
 * @module CookieManager
 * @fileoverview Contains CookieManager class.
 */

/**
 * Manager of cookies for local storage in browser.
 * @class
 */
class CookieManager {
    /**
     * Create a new cookie manager.
     * @constructor
     */
    constructor() {
        this._cookies = {};
    }


    // Initialization and loading

    /**
     * Initialize the cookie manager and load all specified cookies.
     */
    init() {
        this._loadCookies();
    }

    /**
     * Load all specified cookies.
     * @private
     */
    _loadCookies() {
        for (const key in this._cookies) {
            const name = key + "=";
            const dc = decodeURIComponent(document.cookie);
            const ca = dc.split(';');
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i];
                while (c.charAt(0) === ' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) === 0)
                    this._cookies[key] = c.substring(name.length, c.length);
            }
        }
    }

    /**
     * Set which cookies to load upon initialization.
     * @param {Object} cookies Object containing cookie keys and their default values.
     */
    load(cookies = {}) {
        this._cookies = cookies;
    }


    // Adding and access

    /**
     * Set a cookie and its value.
     * @param {string} name Key of cookie
     * @param {string} val Value of cookie
     */
    set(name, val) {
        const d = new Date();
        const days = 30;
        d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
        let expires = "expires="+ d.toUTCString();
        document.cookie = name + "=" + val + ";" + expires + ";path=/";

        this._cookies[name] = val;
    }

    /**
     * Get a cookie.
     * @param {string} key Key of cookie
     * @returns {string} Value of cookie
     */
    get(key) {
        return this._cookies[key];
    }

    /**
     * Check if a cookie exists.
     * @param {string} key Key of cookie
     * @returns {boolean} Whether cookie exists
     */
    has(key) {
        if (!(key in this._cookies))
            return false;

        return this._cookies[key] !== null;
    }
}

export default CookieManager;