-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathCache.ts
59 lines (55 loc) · 1.45 KB
/
Cache.ts
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
const isLocalStorageAvailable: boolean = (() => {
if (!window.localStorage) {
return false
}
try {
const key = "fUjXn2r59"; // A random key
const value = "test";
localStorage.setItem(key, value);
localStorage.getItem(key);
localStorage.removeItem(key);
return true;
} catch (e) {
return false;
}
})();
export function saveToLocalStorage(key: string, value: string, expired: number): number{
if (!isLocalStorageAvailable) {
return -1;
}
const savedItem = {
value: value,
expired: Date.now() + 1000 * expired
};
try {
localStorage.setItem(`casbinjs_${key}`, JSON.stringify(savedItem));
} catch (e) {
throw(e)
// TODO: Process the quotaExceededError
}
return 0;
}
/***
* return: a string.
* If ret == null, it means there is no such user permission.
*/
export function loadFromLocalStorage(key: string): string | null{
if (!isLocalStorageAvailable) {
return null;
}
const itemStr = localStorage.getItem(`casbinjs_${key}`);
// No cache
if (itemStr === null) {
return null;
}
const item = JSON.parse(itemStr);
if (Date.now() > item["expired"]){
localStorage.removeItem(`casbinjs_${key}`);
return null;
} else {
return item['value'];
}
}
export function removeLocalStorage(key: string) {
localStorage.removeItem(`casbinjs_${key}`);
}