AnP/Public/ecma/Managers/CookiesManager.ecma.js

107 lines
2.9 KiB
JavaScript

"use strict";
import {Check} from "../Utils/Check.ecma.js";
import {Common} from "../Utils/Common.ecma.js";
/**
* @typedef {import("../Application/AnP.ecma.js").AnP} AnP
*/
/**
* @class CookiesManager
* @constructor
* @param {!AnP} anp
* @return {void}
* @access public
* @static
*/
export const CookiesManager = (function(){
/**
* @constructs CookiesManager
* @param {!AnP} anp
* @return {void}
* @access private
* @static
*/
const CookiesManager = function(anp){
/** @type {CookiesManager} */
const self = this;
/**
* @returns {void}
* @access private
*/
const constructor = () => {};
/**
* @returns {Object.<string, Any|null>}
* @access public
*/
this.to_dictionary = () => document.cookie.split(";").map(cookie => cookie.trim().split("=")).reduce((dictionary, [key, value]) => {
dictionary[key] = value;
return dictionary;
}, {});
/**
*
* @param {!string} name
* @param {any|null} value
* @param {!(boolean|Object.<string, Any|null>|Array.<any|null>)} options
* @returns
*/
this.set = (name, value, options = {}) => {
if(Common.get_value("overwrite", (
Check.is_boolean ? {overwrite : options} :
options), false) || !self.has(name)){
document.cookie = (
`${name}=${value}` +
(Common.get_value("expires", options) ? `; expires=${options.expires.toUTCString()}` : "") +
(Common.get_value("path", options) ? `; path=${options.path}` : "") +
(Common.get_value("domain", options) ? `; domain=${options.domain}` : "") +
(Common.get_value("secure", options) ? `; secure` : "")
);
return true;
};
return false;
};
/**
* @param {!string} name
* @returns {boolean}
* @access public
*/
this.has = name => name in self.to_dictionary();
/**
* @param {!string} name
* @returns {string|null}
* @access public
*/
this.get = name => self.to_dictionary()[name] || null;
/**
* @param {!string} name
* @param {!(boolean|Object.<string, any|null>|Array.<any|null>)} options
* @returns {boolean}
* @access public
*/
this.delete = (name, options = {}) => {
if(self.has(name)){
self.set(name, "", {
expires : new Date(0),
...Common.get_dictionary(options)
});
return true;
};
return false;
};
constructor();
};
return CookiesManager;
})();