| 4 | >; |
| 5 | |
| 6 | export default function Storage(): StorageWrapper { |
| 7 | const inMemoryStorage: { [key: string]: string } = {}; |
| 8 | |
| 9 | function isLocalStorageEnabled() { |
| 10 | try { |
| 11 | return 'localStorage' in window && window.localStorage !== null; |
| 12 | } catch (e) { |
| 13 | return false; |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | function getItem(key: string): string | null { |
| 18 | if (isLocalStorageEnabled()) { |
| 19 | return localStorage.getItem(key); |
| 20 | } |
| 21 | return inMemoryStorage[key] ?? null; |
| 22 | } |
| 23 | |
| 24 | function setItem(key: string, value: string): void { |
| 25 | if (isLocalStorageEnabled()) { |
| 26 | localStorage.setItem(key, value); |
| 27 | } else { |
| 28 | inMemoryStorage[key] = value; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | function removeItem(key: string): void { |
| 33 | if (isLocalStorageEnabled()) { |
| 34 | localStorage.removeItem(key); |
| 35 | } else { |
| 36 | delete inMemoryStorage[key]; |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | function clear(): void { |
| 41 | if (isLocalStorageEnabled()) { |
| 42 | localStorage.clear(); |
| 43 | } else { |
| 44 | Object.keys(inMemoryStorage).forEach((key) => { |
| 45 | delete inMemoryStorage[key]; |
| 46 | }); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | return { |
| 51 | getItem, |
| 52 | setItem, |
| 53 | removeItem, |
| 54 | clear, |
| 55 | }; |
| 56 | } |
| 57 | export const storageWrapper = Storage(); |