All files index.ts

94.23% Statements 278/295
76.19% Branches 32/42
100% Functions 13/13
94.23% Lines 278/295

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 2961x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                   1x 1x 1x 1x 1x     1x 1x 1x 1x 2x 2x 1x 1x 1x 2x     2x 1x 1x 1x 1x 1x 1x 18x 18x 18x     18x 18x 7x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 1x 1x 1x 1x 5x 5x 1x 1x 1x 1x 1x 1x 1x 19x 18x 18x 18x 18x 7x 18x 3x 3x 3x 3x 3x 3x 3x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 19x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 7x 7x 5x 5x 5x 1x 1x 1x 28x 28x 28x 28x 28x 23x 23x 23x 23x 23x 23x 23x 23x 28x 28x 28x 28x 28x     28x 28x 1x 1x 1x 1x 1x 1x 1x 1x 1x 67x 67x 1x 1x 1x  
/*
 * @Author: Lyon lyon@lyon.lv
 * @Date: 2023-05-25 12:03:52
 * @LastEditors: Lyon lyon@lyon.lv
 * @LastEditTime: 2024-04-19 12:13:10
 * @FilePath: /temp-store/lib/index.ts
 * @Description:
 */
import PersistentData from '@lyon/persistent-data'
 
/**
 * TempStore 类的定义
 */
interface TempStoreInterface {
  set: <T>({}: SetObject<T>) => void
  get: <T = any>(key: string) => T | undefined
  delete: ({}: DeleteObject) => void
  getAllValueList: () => Array<any>
  destroy: (isExecute?: boolean) => void
  load: (key: string) => void
  unload: () => void
}
 
/**
 * set 方法参数类型
 */
interface SetObject<T> {
  key: string
  value: T
  time: number
  callback?: DeleteCallbackFn<T>
  isSave?: boolean // 当前数据是否持久化保存
}
 
// 批量删除参数
interface DeleteMultipleObject {
  key: string
  isExecute?: boolean | undefined // 是否执行删除回调 默认 true
}
 
/**
 * delete 方法参数类型
 */
interface DeleteObject extends DeleteMultipleObject {
  isSave?: boolean // 当前数据是否持久化保存
}
 
/**
 * 删除函数回调参数类型
 */
type DeleteCallbackFn<T> = ({ key, value }: { key: string; value: T }) => void
 
interface TempStoreSaveValueItemType<T> {
  value: T // 需要保存的数据
  create: number // 创建时间 ms
  time: number // 保存的时间 ms
}
 
interface TempStoreValueItemType<T = any> extends TempStoreSaveValueItemType<T> {
  deleteId: number | NodeJS.Timeout // settimeout 的回调 id
  deleteCallback?: DeleteCallbackFn<T> // 删除事件的回调
}
 
interface TempStoreSaveValueType<T> {
  [key: string]: TempStoreSaveValueItemType<T>
}
 
/**
 * 内部临时数据类型
 */
interface TempStoreValueType<T> {
  [key: string]: TempStoreValueItemType<T>
}
 
class TempStore implements TempStoreInterface {
  private $_TempStore: TempStoreValueType<any>
  private Persistent: PersistentData<TempStoreSaveValueType<any>> | null
  private readonly isDebug: boolean
  private readonly isNode: boolean // 当前环境是否是 node
 
  public constructor(isDebug?: Boolean) {
    this.isDebug = Boolean(isDebug)
    this.$_TempStore = {}
    this.isNode = typeof (window as any) === 'undefined'
    this.Persistent = null
  }
 
  // 启用数据持久化
  public load(key: string) {
    try {
      // 如果多次调用先删除旧的再创建新的
      this.unload()
 
      if (!this.Persistent) {
        this.Persistent = new PersistentData(key, this.$_TempStore, this.isDebug)
        // 从持久化中获取数据
        this.Persistent.read()
 
        const keys = Object.keys(this.Persistent.data)
        const current = new Date().getTime()
        for (const key of keys) {
          const { value, time, create } = this.Persistent.data[key]

          if (current < create + time) {
            // 没过期
            const newTime = create + time - current // 新的删除时间
            // 赋值
            this.set({ key, value, time: newTime, isSave: false })
          }
        }
 
        // 保存一下最新的数据
        this.save()
      }
    } catch (e) {
      this.log(e)
    }
  }
 
  // 卸载数据持久化并删除数据
  public unload() {
    try {
      if (this.Persistent) {
        this.Persistent.remove()
        this.Persistent = null
      }
    } catch (e) {
      this.log(e)
    }
  }
 
  /**
   * 保存临时数据
   * @param {Object} obj 参数对象 {key:键名,value:键值,time:超时时间(默认0ms),callback: 数据删除后的回调(参数为删除的数据 key value 对象),isSave: 是否持久化保存该数据 默认触发保存}
   */
  public set<T>({ key = 'normal', value, time = 0, callback, isSave = true }: SetObject<T>): void {
    // 已存在的 key 先删除 再重新赋值
    // 清空原有的定时器id
    if (this.$_TempStore[key]) {
      clearTimeout(this.$_TempStore[key].deleteId)
    }
    // 设置删除定时器
    const deleteId = setTimeout(() => {
      this.delete({ key })
    }, time)
 
    this.$_TempStore[key] = {
      value,
      deleteId,
      time,
      create: new Date().getTime(),
      deleteCallback: callback
    }
 
    isSave && this.save()
 
    this.log(
      `临时数据---保存[${JSON.stringify({
        key,
        value,
        time
      })}]成功${
        this.isNode ? `此时内存占用量为[${global.process.memoryUsage().heapUsed}]字节` : ''
      }`
    )
  }
 
  /**
   * 获取临时数据
   * @param {String} key key值
   */
  public get<T = any>(key: string): T | undefined {
    return this.$_TempStore[key] ? this.$_TempStore[key].value : undefined
  }
 
  /**
   * 删除指定临时数据
   * @param {String} key key值
   * @param {Object} params 是否执行删除回调 默认执行
   */
  public delete({ key, isExecute = true, isSave = true }: DeleteObject) {
    if (this.$_TempStore[key]) {
      // 清空原有的定时器id
      clearTimeout(this.$_TempStore[key].deleteId)
      if (
        isExecute &&
        Object.prototype.toString.call(this.$_TempStore[key].deleteCallback) === '[object Function]'
      ) {
        // 已经判断过是否是空
        ;(this.$_TempStore[key].deleteCallback as DeleteCallbackFn<any>)({
          key,
          value: this.$_TempStore[key].value
        })
        this.log(`临时数据---执行[${key}]删除数据回调成功`)
      }
 
      ;(this.$_TempStore as any)[key] = null
      delete this.$_TempStore[key] // 删除数据 强制设置为 any
 
      isSave && this.save()
 
      this.log(
        `临时数据---删除[${key}]成功${
          this.isNode ? ` 此时内存占用量为[${global.process.memoryUsage().heapUsed}]字节` : ''
        }`
      )
    }
  }
 
  /**
   * 批量删除数据
   */
  public deleteMultiple(list: DeleteMultipleObject[]) {
    for (const item of list) {
      this.delete({ key: item.key, isExecute: item.isExecute, isSave: false })
    }
 
    this.save()
  }
 
  /**
   * 返回一个所有数据的列表
   */
  public getAllValueList(): Array<any> {
    return Object.values(this.$_TempStore).map((item) => item.value)
  }
 
  /**
   * 返回一个所有数据 key 的列表
   */
  public getAllKeyList(): Array<any> {
    return Object.keys(this.$_TempStore)
  }
 
  /**
   * 返回一个所有数据项的列表
   */
  public getAllItemList(): Array<any> {
    return Object.keys(this.$_TempStore).map((key) => ({
      key,
      value: this.$_TempStore[key].value
    }))
  }
 
  /**
   * 销毁当前 temp data
   * @param {Boolean} isExecute 是否执行删除回调 默认执行
   */
  public destroy(isExecute?: boolean | undefined): void {
    const keys = Object.keys(this.$_TempStore)
    for (const key of keys) {
      this.delete({ key, isExecute })
    }
 
    this.save()
  }
 
  // 持久化保存方法
  private save() {
    if (this.Persistent) {
      try {
        const keys = Object.keys(this.$_TempStore)
        let data: TempStoreSaveValueType<any> = {}
        for (const key of keys) {
          const { value, time, create } = this.$_TempStore[key]
 
          data[key] = {
            value,
            time,
            create
          }
        }
 
        this.Persistent.data = data
        this.Persistent.write()
        this.log('数据持久化保存成功')
      } catch (e) {
        this.log(e)
      }
    }
  }
 
  /**
   * 打印日志信息。
   * 仅当`isDebug`为`true`时,才会将消息及可选参数输出到控制台。
   * @param message 可选,要打印的主要消息内容。
   * @param optionalParams 可选,一个或多个额外的参数,将会与主要消息一起打印。
   * @returns 无返回值。
   */
  private log(message?: any): void {
    this.isDebug && console.log(message)
  }
}
 
export default TempStore