-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathls.ts
More file actions
62 lines (49 loc) · 1.68 KB
/
Copy pathls.ts
File metadata and controls
62 lines (49 loc) · 1.68 KB
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
import { effect } from './f'
import { secretKey } from './config'
import CryptoJS from 'crypto-js'
interface LocalStorageMap {
tableFootball: State
}
export const set = <K extends keyof LocalStorageMap>(
key: K,
value: LocalStorageMap[K]
): void => { localStorage.setItem(key, encryptData(value)) }
export const has = (key: keyof LocalStorageMap): boolean =>
Boolean(localStorage.getItem(key))
export const get = <K extends keyof LocalStorageMap>(
key: K
): LocalStorageMap[K] | null => {
const value = localStorage.getItem(key)
if (value === null || value === undefined) return null
try {
return decryptData(value)
} catch {
// HOTFIX: fallback for old serialization format
return value as never
}
}
export const del = (key: keyof LocalStorageMap): void => { localStorage.removeItem(key) }
export const clear = (): void => { localStorage.clear() }
export const cache = async <K extends keyof LocalStorageMap>(
key: K,
fetch: () => Promise<LocalStorageMap[K]>
): Promise<LocalStorageMap[K]> => {
const cached = get(key)
return (cached !== null && cached !== undefined)
? await Promise.resolve<LocalStorageMap[K]>(cached)
: await fetch().then(effect((x) => { set(key, x) }))
}
const encryptData = <K extends keyof LocalStorageMap>(
data: LocalStorageMap[K]
): string => {
const encryptedData = CryptoJS.AES.encrypt(
JSON.stringify(data),
secretKey
).toString()
return encryptedData
}
const decryptData = (encryptedData: string): LocalStorageMap[keyof LocalStorageMap] => {
const decryptedBytes = CryptoJS.AES.decrypt(encryptedData, secretKey)
const decryptedData = JSON.parse(decryptedBytes.toString(CryptoJS.enc.Utf8))
return decryptedData
}