zhongrj
2025-03-28 4ff3eee77b41466d08117970970d01be6e48ffe1
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
 * @Author: GuLiMmo 2820890765@qq.com
 * @Date: 2024-08-27 15:37:44
 * @LastEditors: GuLiMmo 2820890765@qq.com
 * @LastEditTime: 2024-08-27 15:55:14
 * @FilePath: /drone-web/src/utils/store.ts
 * @Description:
 * Copyright (c) 2024 by GuLiMmo, All Rights Reserved.
 */
import { validatenull } from '@/utils/validate'
 
/**
 * 存储localStorage
 */
export const setStore = (params: { name: string, content: any, type?: any }) => {
  const { name, content, type } = params
  const obj = {
    dataType: typeof content,
    content: content,
    type: type,
    datetime: new Date().getTime(),
  }
  if (type) window.sessionStorage.setItem(name, JSON.stringify(obj))
  else window.localStorage.setItem(name, JSON.stringify(obj))
}
/**
 * 获取localStorage
 */
 
export const getStore = (params: { name: any; type?: string; debug?: any }) => {
  const { name, debug } = params
  let obj: any = {}
  let content: string | number = ''
  obj = window.sessionStorage.getItem(name)
  if (validatenull(obj)) obj = window.localStorage.getItem(name)
  if (validatenull(obj)) return
  try {
    obj = JSON.parse(obj)
  } catch {
    return obj
  }
  if (debug) {
    return obj
  }
  if (obj.dataType === 'string') {
    content = obj.content
  } else if (obj.dataType === 'number') {
    content = Number(obj.content)
  } else if (obj.dataType === 'boolean') {
    // eslint-disable-next-line no-eval
    content = eval(obj.content)
  } else if (obj.dataType === 'object') {
    content = obj.content
  }
  return content
}
/**
 * 删除localStorage
 */
export const removeStore = (params: { name: string; type?: string }) => {
  const { name, type } = params
  if (type) {
    window.sessionStorage.removeItem(name)
  } else {
    window.localStorage.removeItem(name)
  }
}
 
/**
 * 获取全部localStorage
 */
export const getAllStore = (params: { type: string }) => {
  const list = []
  const { type } = params
  if (type) {
    for (let i = 0; i <= window.sessionStorage.length; i++) {
      list.push({
        name: window.sessionStorage.key(i),
        content: getStore({
          name: window.sessionStorage.key(i),
          type: 'session',
        }),
      })
    }
  } else {
    for (let i = 0; i <= window.localStorage.length; i++) {
      list.push({
        name: window.localStorage.key(i),
        content: getStore({
          name: window.localStorage.key(i),
        }),
      })
    }
  }
  return list
}
 
/**
 * 清空全部localStorage
 */
export const clearStore = (params: { type: string }) => {
  const { type } = params
  if (type) {
    window.sessionStorage.clear()
  } else {
    window.localStorage.clear()
  }
}