yangfeng
2023-11-29 d7c06cca16d12ecf5d0f233395dcf6062261b39b
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
import AES from "crypto-js/aes"
import ENC_UTF8 from "crypto-js/enc-utf8"
import WebStorageCache from "web-storage-cache"
import { LOCAL_ENCRYPTED_KEY } from "@/common/config"
 
const cache = new WebStorageCache()
const isEncrypt = true
const isEncryptPartial = true
 
function getCache(key) {
  const encryptValue = cache.get(key)
  if (encryptValue === null) {
    return null
  }
  const bytes = AES.decrypt(encryptValue, LOCAL_ENCRYPTED_KEY)
  const plaintext = bytes.toString(ENC_UTF8)
  return JSON.parse(plaintext)
}
 
function setCache(key, value) {
  const encryptValue = AES.encrypt(JSON.stringify(value), LOCAL_ENCRYPTED_KEY).toString()
  return cache.set(key, encryptValue)
}
 
function deleteCache(key) {
  return cache.delete(key)
}
 
function getCacheWrapper(key) {
  if (isEncrypt || isEncryptPartial) {
    return getCache(key)
  } else {
    return cache.get(key)
  }
}
 
function setCacheWrapper(key, value) {
  if (isEncrypt || isEncryptPartial) {
    return setCache(key, value)
  } else {
    return cache.set(key, value)
  }
}
 
export const wsCache = {
  get: getCacheWrapper,
  set: setCacheWrapper,
  delete: deleteCache
}