|
1 | 1 | const SESSION_STORAGE_INITIALIZED = 'eppo-session-storage-initialized';
|
2 | 2 |
|
3 | 3 | export class EppoSessionStorage {
|
4 |
| - // Fallback storage in case the user has disabled session storage in the browser. |
5 |
| - private fallbackStorage: Record<string, string> = {}; |
6 |
| - |
7 | 4 | public get<T>(key: string): T {
|
8 |
| - let serializedEntry; |
9 | 5 | if (this.hasWindowSessionStorage()) {
|
10 |
| - serializedEntry = window.sessionStorage.getItem(key); |
11 |
| - } else { |
12 |
| - serializedEntry = this.fallbackStorage[key]; |
13 |
| - } |
14 |
| - if (serializedEntry) { |
15 |
| - return JSON.parse(serializedEntry); |
| 6 | + const serializedEntry = window.sessionStorage.getItem(key); |
| 7 | + if (serializedEntry) { |
| 8 | + return JSON.parse(serializedEntry); |
| 9 | + } |
16 | 10 | }
|
17 | 11 | return null;
|
18 | 12 | }
|
19 | 13 |
|
| 14 | + // Checks whether session storage is enabled in the browser (the user might have disabled it). |
20 | 15 | private hasWindowSessionStorage(): boolean {
|
21 | 16 | try {
|
22 | 17 | return typeof window !== 'undefined' && !!window.sessionStorage;
|
23 | 18 | } catch {
|
24 |
| - // Some browsers throw an error if session storage is disabled and you try to access it |
| 19 | + // Chrome throws an error if session storage is disabled and you try to access it |
25 | 20 | return false;
|
26 | 21 | }
|
27 | 22 | }
|
28 | 23 |
|
29 |
| - public isSessionStorageInitialized(): boolean { |
| 24 | + public isInitialized(): boolean { |
30 | 25 | return !!this.get(SESSION_STORAGE_INITIALIZED);
|
31 | 26 | }
|
32 | 27 |
|
33 | 28 | public setEntries<T>(entries: Record<string, T>) {
|
34 | 29 | if (this.hasWindowSessionStorage()) {
|
35 |
| - this.setEntriesInSessionStorage(entries); |
36 |
| - } else { |
37 |
| - this.setEntriesInFallbackStorage(entries); |
| 30 | + Object.entries(entries).forEach(([key, val]) => { |
| 31 | + window.sessionStorage.setItem(key, JSON.stringify(val)); |
| 32 | + }); |
| 33 | + window.sessionStorage.setItem(SESSION_STORAGE_INITIALIZED, 'true'); |
38 | 34 | }
|
39 | 35 | }
|
40 |
| - |
41 |
| - private setEntriesInSessionStorage<T>(entries: Record<string, T>) { |
42 |
| - Object.entries(entries).forEach(([key, val]) => { |
43 |
| - window.sessionStorage.setItem(key, JSON.stringify(val)); |
44 |
| - }); |
45 |
| - window.sessionStorage.setItem(SESSION_STORAGE_INITIALIZED, 'true'); |
46 |
| - } |
47 |
| - |
48 |
| - private setEntriesInFallbackStorage<T>(entries: Record<string, T>) { |
49 |
| - Object.entries(entries).forEach(([key, val]) => { |
50 |
| - this.fallbackStorage[key] = JSON.stringify(val); |
51 |
| - }); |
52 |
| - } |
53 | 36 | }
|
0 commit comments