办学质量监测教学评价系统
shenrongliang
2025-06-13 11d86cc6c26bb4f709e407acadf4805c2024e79f
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
interface StorageData<T = any> {
  data: T
  expire: number | null
}
 
export function createLocalStorage(options?: { expire?: number | null }) {
  // token默认保存7天
  const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7
 
  const { expire } = Object.assign({ expire: DEFAULT_CACHE_TIME }, options)
 
  function set<T = any>(key: string, data: T) {
    const storageData: StorageData<T> = {
      data,
      expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
    }
 
    const json = JSON.stringify(storageData)
    window.localStorage.setItem(key, json)
  }
 
  function get(key: string) {
    const json = window.localStorage.getItem(key)
 
    if (json) {
      let storageData: StorageData | null = null
 
      try {
        storageData = JSON.parse(json)
      }
      catch {
        // Prevent failure
      }
 
      if (storageData) {
        const { data, expire } = storageData
        if (expire === null || expire >= Date.now())
          return data
      }
 
      remove(key)
      return null
    }
  }
 
  function remove(key: string) {
    window.localStorage.removeItem(key)
  }
 
  function clear() {
    window.localStorage.clear()
  }
 
  return { set, get, remove, clear }
}
 
export const ls = createLocalStorage()
 
export const ss = createLocalStorage({ expire: null })