File size: 2,292 Bytes
1dbc34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
 * Centralized localStorage abstraction module
 *
 * Provides type-safe wrappers for all localStorage operations.
 * All localStorage access should go through this module to ensure
 * consistent error handling and environment checks.
 */

/**
 * Check if localStorage is available in the current environment
 */
function isStorageAvailable(): boolean {
  return typeof window !== 'undefined' && window.localStorage !== undefined;
}

/**
 * Get an item from localStorage
 * @param key - The storage key
 * @returns The stored value or null if not found/unavailable
 */
export function getItem(key: string): string | null {
  if (!isStorageAvailable()) return null;
  try {
    return window.localStorage.getItem(key);
  } catch {
    return null;
  }
}

/**
 * Set an item in localStorage
 * @param key - The storage key
 * @param value - The value to store
 * @returns true if successful, false otherwise
 */
export function setItem(key: string, value: string): boolean {
  if (!isStorageAvailable()) return false;
  try {
    window.localStorage.setItem(key, value);
    return true;
  } catch {
    return false;
  }
}

/**
 * Remove an item from localStorage
 * @param key - The storage key to remove
 * @returns true if successful, false otherwise
 */
export function removeItem(key: string): boolean {
  if (!isStorageAvailable()) return false;
  try {
    window.localStorage.removeItem(key);
    return true;
  } catch {
    return false;
  }
}

/**
 * Get a JSON-parsed item from localStorage
 * @param key - The storage key
 * @returns The parsed value or null if not found/invalid
 */
export function getJSON<T>(key: string): T | null {
  const value = getItem(key);
  if (!value) return null;
  try {
    return JSON.parse(value) as T;
  } catch {
    return null;
  }
}

/**
 * Set a JSON-stringified item in localStorage
 * @param key - The storage key
 * @param value - The value to stringify and store
 * @returns true if successful, false otherwise
 */
export function setJSON<T>(key: string, value: T): boolean {
  try {
    return setItem(key, JSON.stringify(value));
  } catch {
    return false;
  }
}

/**
 * Storage module for named exports
 */
export const storage = {
  getItem,
  setItem,
  removeItem,
  getJSON,
  setJSON,
  isAvailable: isStorageAvailable,
};