UNPKG

2.08 kBJavaScriptView Raw
1import * as Cookies from 'js-cookie';
2
3/** @class */
4export default class CookieStorage {
5 /**
6 * Constructs a new CookieStorage object
7 * @param {object} data Creation options.
8 * @param {string} data.domain Cookies domain (mandatory).
9 * @param {string} data.path Cookies path (default: '/')
10 * @param {integer} data.expires Cookie expiration (in days, default: 365)
11 * @param {boolean} data.secure Cookie secure flag (default: true)
12 */
13 constructor(data) {
14 if (data.domain) {
15 this.domain = data.domain;
16 } else {
17 throw new Error('The domain of cookieStorage can not be undefined.');
18 }
19 if (data.path) {
20 this.path = data.path;
21 } else {
22 this.path = '/';
23 }
24 if (Object.prototype.hasOwnProperty.call(data, 'expires')) {
25 this.expires = data.expires;
26 } else {
27 this.expires = 365;
28 }
29 if (Object.prototype.hasOwnProperty.call(data, 'secure')) {
30 this.secure = data.secure;
31 } else {
32 this.secure = true;
33 }
34 }
35
36 /**
37 * This is used to set a specific item in storage
38 * @param {string} key - the key for the item
39 * @param {object} value - the value
40 * @returns {string} value that was set
41 */
42 setItem(key, value) {
43 Cookies.set(key, value, {
44 path: this.path,
45 expires: this.expires,
46 domain: this.domain,
47 secure: this.secure,
48 });
49 return Cookies.get(key);
50 }
51
52 /**
53 * This is used to get a specific key from storage
54 * @param {string} key - the key for the item
55 * This is used to clear the storage
56 * @returns {string} the data item
57 */
58 getItem(key) {
59 return Cookies.get(key);
60 }
61
62 /**
63 * This is used to remove an item from storage
64 * @param {string} key - the key being set
65 * @returns {string} value - value that was deleted
66 */
67 removeItem(key) {
68 return Cookies.remove(key, {
69 path: this.path,
70 domain: this.domain,
71 secure: this.secure,
72 });
73 }
74
75 /**
76 * This is used to clear the storage
77 * @returns {string} nothing
78 */
79 clear() {
80 const cookies = Cookies.get();
81 let index;
82 for (index = 0; index < cookies.length; ++index) {
83 Cookies.remove(cookies[index]);
84 }
85 return {};
86 }
87}