UNPKG

2.84 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 * @param {string} data.sameSite Cookie request behaviour (default: null)
13 */
14 constructor(data) {
15 if (data.domain) {
16 this.domain = data.domain;
17 } else {
18 throw new Error('The domain of cookieStorage can not be undefined.');
19 }
20 if (data.path) {
21 this.path = data.path;
22 } else {
23 this.path = '/';
24 }
25 if (Object.prototype.hasOwnProperty.call(data, 'expires')) {
26 this.expires = data.expires;
27 } else {
28 this.expires = 365;
29 }
30 if (Object.prototype.hasOwnProperty.call(data, 'secure')) {
31 this.secure = data.secure;
32 } else {
33 this.secure = true;
34 }
35 if (Object.prototype.hasOwnProperty.call(data, 'sameSite')) {
36 if (!['strict','lax','none'].includes(data.sameSite)) {
37 throw new Error(
38 'The sameSite value of cookieStorage must be "lax", "strict" or "none".'
39 );
40 }
41 if (data.sameSite === 'none' && !this.secure) {
42 throw new Error(
43 'sameSite = None requires the Secure attribute in latest browser versions.'
44 );
45 }
46 this.sameSite = data.sameSite;
47 } else {
48 this.sameSite = null;
49 }
50 }
51
52 /**
53 * This is used to set a specific item in storage
54 * @param {string} key - the key for the item
55 * @param {object} value - the value
56 * @returns {string} value that was set
57 */
58 setItem(key, value) {
59 const options = {
60 path: this.path,
61 expires: this.expires,
62 domain: this.domain,
63 secure: this.secure,
64 };
65
66 if (this.sameSite) {
67 options.sameSite = this.sameSite;
68 }
69
70 Cookies.set(key, value, options);
71 return Cookies.get(key);
72 }
73
74 /**
75 * This is used to get a specific key from storage
76 * @param {string} key - the key for the item
77 * This is used to clear the storage
78 * @returns {string} the data item
79 */
80 getItem(key) {
81 return Cookies.get(key);
82 }
83
84 /**
85 * This is used to remove an item from storage
86 * @param {string} key - the key being set
87 * @returns {string} value - value that was deleted
88 */
89 removeItem(key) {
90 const options = {
91 path: this.path,
92 expires: this.expires,
93 domain: this.domain,
94 secure: this.secure,
95 };
96
97 if (this.sameSite) {
98 options.sameSite = this.sameSite;
99 }
100
101 return Cookies.remove(key, options);
102 }
103
104 /**
105 * This is used to clear the storage
106 * @returns {string} nothing
107 */
108 clear() {
109 const cookies = Cookies.get();
110 let index;
111 for (index = 0; index < cookies.length; ++index) {
112 Cookies.remove(cookies[index]);
113 }
114 return {};
115 }
116}