1 | import * as Cookies from 'js-cookie';
|
2 |
|
3 |
|
4 | export default class CookieStorage {
|
5 | |
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
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 |
|
54 |
|
55 |
|
56 |
|
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 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 | getItem(key) {
|
81 | return Cookies.get(key);
|
82 | }
|
83 |
|
84 | |
85 |
|
86 |
|
87 |
|
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 |
|
106 |
|
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 | }
|