1 | import Cookies from 'universal-cookie';
|
2 | import { browserOrNode } from '../JS';
|
3 | var isBrowser = browserOrNode().isBrowser;
|
4 | var UniversalStorage = (function () {
|
5 | function UniversalStorage(context) {
|
6 | if (context === void 0) { context = {}; }
|
7 | this.cookies = new Cookies();
|
8 | this.store = isBrowser ? window.localStorage : Object.create(null);
|
9 | this.cookies = context.req
|
10 | ? new Cookies(context.req.headers.cookie)
|
11 | : new Cookies();
|
12 | Object.assign(this.store, this.cookies.getAll());
|
13 | }
|
14 | Object.defineProperty(UniversalStorage.prototype, "length", {
|
15 | get: function () {
|
16 | return Object.entries(this.store).length;
|
17 | },
|
18 | enumerable: true,
|
19 | configurable: true
|
20 | });
|
21 | UniversalStorage.prototype.clear = function () {
|
22 | var _this = this;
|
23 | Array.from(new Array(this.length))
|
24 | .map(function (_, i) { return _this.key(i); })
|
25 | .forEach(function (key) { return _this.removeItem(key); });
|
26 | };
|
27 | UniversalStorage.prototype.getItem = function (key) {
|
28 | return this.getLocalItem(key);
|
29 | };
|
30 | UniversalStorage.prototype.getLocalItem = function (key) {
|
31 | return Object.prototype.hasOwnProperty.call(this.store, key)
|
32 | ? this.store[key]
|
33 | : null;
|
34 | };
|
35 | UniversalStorage.prototype.getUniversalItem = function (key) {
|
36 | return this.cookies.get(key);
|
37 | };
|
38 | UniversalStorage.prototype.key = function (index) {
|
39 | return Object.keys(this.store)[index];
|
40 | };
|
41 | UniversalStorage.prototype.removeItem = function (key) {
|
42 | this.removeLocalItem(key);
|
43 | this.removeUniversalItem(key);
|
44 | };
|
45 | UniversalStorage.prototype.removeLocalItem = function (key) {
|
46 | delete this.store[key];
|
47 | };
|
48 | UniversalStorage.prototype.removeUniversalItem = function (key) {
|
49 | this.cookies.remove(key, {
|
50 | path: '/',
|
51 | });
|
52 | };
|
53 | UniversalStorage.prototype.setItem = function (key, value) {
|
54 | this.setLocalItem(key, value);
|
55 |
|
56 |
|
57 |
|
58 | var tokenType = key.split('.').pop();
|
59 | switch (tokenType) {
|
60 |
|
61 | case 'LastAuthUser':
|
62 |
|
63 | case 'accessToken':
|
64 |
|
65 | case 'idToken':
|
66 | this.setUniversalItem(key, value);
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | }
|
75 | };
|
76 | UniversalStorage.prototype.setLocalItem = function (key, value) {
|
77 | this.store[key] = value;
|
78 | };
|
79 | UniversalStorage.prototype.setUniversalItem = function (key, value) {
|
80 | this.cookies.set(key, value, {
|
81 | path: '/',
|
82 |
|
83 | sameSite: true,
|
84 |
|
85 | secure: window.location.hostname === 'localhost' ? false : true,
|
86 | });
|
87 | };
|
88 | return UniversalStorage;
|
89 | }());
|
90 | export { UniversalStorage };
|
91 |
|
\ | No newline at end of file |