-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.ts
67 lines (60 loc) · 1.57 KB
/
storage.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
60
61
62
63
64
65
66
67
import { isApiMocked } from "../../windowVars";
export enum StorageKey {
LANGUAGE = "lang",
AUTH = "auth",
}
export enum StorageType {
LOCAL,
SESSION
}
export const COOKIES_EXPIRY = 365;
const getStorageKey = (key: string, uid?: number) => {
if (isApiMocked()) {
return `${key}`;
} else {
return `${key}${uid ? "-" + uid : ""}`;
}
};
export const fromStorage = (
basedKey: string,
defauleValue: any,
uid?: number,
type: StorageType = StorageType.LOCAL
) => {
const key = getStorageKey(basedKey, uid);
let item;
if (type === StorageType.LOCAL) {
item = localStorage.getItem(key);
} else if (type === StorageType.SESSION) {
item = sessionStorage.getItem(key);
}
if (item === null) {
return defauleValue;
}
return item;
};
export const toStorage = (
basedKey: string,
value: any,
uid?: number,
type: StorageType = StorageType.LOCAL
) => {
const key = getStorageKey(basedKey, uid);
if (type === StorageType.LOCAL) {
localStorage.setItem(key, value);
} else if (type === StorageType.SESSION) {
sessionStorage.setItem(key, value);
}
};
export const removeStorage = (
basedKey: string,
uid?: number,
type: StorageType = StorageType.LOCAL
) => {
const key = getStorageKey(basedKey, uid);
if (type === StorageType.LOCAL) {
localStorage.removeItem(key);
} else if (type === StorageType.SESSION) {
sessionStorage.removeItem(key);
}
};