blob: a24096a670a348bf9ef86346d316f8e943dc577b (
plain) (
blame)
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
|
/*** EXPORT ------------------------------------------- ***/
export type Storage = {
get<T>(key: string): T | null;
remove(key: string): void;
set<T>(key: string, value: T): void;
};
export function createLocalStorage(namespace: string): Storage {
const prefix = `${namespace}:`;
function available(): boolean {
try {
return typeof globalThis.localStorage !== "undefined";
} catch {
return false;
}
}
return {
get<T>(key: string): T | null {
if (!available())
return null;
const raw = globalThis.localStorage.getItem(prefix + key);
if (raw === null)
return null;
try {
return JSON.parse(raw) as T;
} catch {
return null;
}
},
remove(key: string): void {
if (!available())
return;
globalThis.localStorage.removeItem(prefix + key);
},
set<T>(key: string, value: T): void {
if (!available())
return;
globalThis.localStorage.setItem(prefix + key, JSON.stringify(value));
}
};
}
export function createMemoryStorage(): Storage {
const store = new Map<string, string>();
return {
get<T>(key: string): T | null {
const raw = store.get(key);
if (raw === undefined)
return null;
try {
return JSON.parse(raw) as T;
} catch {
return null;
}
},
remove(key: string): void {
store.delete(key);
},
set<T>(key: string, value: T): void {
store.set(key, JSON.stringify(value));
}
};
}
|