/ src / lib / app / safe-storage.ts
safe-storage.ts
 1  function canUseLocalStorage(): boolean {
 2    if (typeof window === 'undefined') return false
 3    try {
 4      return !!window.localStorage
 5    } catch {
 6      return false
 7    }
 8  }
 9  
10  export function safeStorageGet(key: string): string | null {
11    if (!canUseLocalStorage()) return null
12    try {
13      return window.localStorage.getItem(key)
14    } catch {
15      return null
16    }
17  }
18  
19  export function safeStorageSet(key: string, value: string): boolean {
20    if (!canUseLocalStorage()) return false
21    try {
22      window.localStorage.setItem(key, value)
23      return true
24    } catch {
25      return false
26    }
27  }
28  
29  export function safeStorageRemove(key: string): boolean {
30    if (!canUseLocalStorage()) return false
31    try {
32      window.localStorage.removeItem(key)
33      return true
34    } catch {
35      return false
36    }
37  }
38  
39  export function safeStorageGetJson<T>(key: string, fallback: T): T {
40    const raw = safeStorageGet(key)
41    if (!raw) return fallback
42    try {
43      return JSON.parse(raw) as T
44    } catch {
45      return fallback
46    }
47  }