美文网首页
uni-app 自定义缓存机制

uni-app 自定义缓存机制

作者: 站着瞌睡 | 来源:发表于2021-03-03 00:09 被阅读0次
    const cacheMap = new Map()
    let timeoutDefault = 1200
    
    function isTimeout(name: string) {
      const data = cacheMap.get(name)
      if (!data) return true
      if (data.timeout === 0) return false
      const currentTime = Date.now()
      const overTime = (currentTime - data.createTime) / 1000
      if (overTime > data.timeout) {
        cacheMap.delete(name)
        if (name.startsWith('_')) {
          try {
            uni.removeStorageSync(name)
          } catch (e) {
            console.log(e)
          }
        }
        return true
      }
      return false
    }
    
    class CacheCell {
      private data: any
      private timeout: number
      private createTime: number
      constructor(data: any, timeout: number) {
        this.data = data
        this.timeout = timeout
        this.createTime = Date.now()
      }
    }
    
    class MinCache {
      constructor(timeout = timeoutDefault) {
        try {
          const res = uni.getStorageInfoSync()
          res.keys.forEach((name) => {
            try {
              const value = uni.getStorageSync(name)
              cacheMap.set(name, value)
            } catch (e) {
              console.log(e)
            }
          })
        } catch (e) {
          console.log(e)
        }
        timeoutDefault = timeout
      }
      set(name: string, data: any, timeout = timeoutDefault) {
        const cachecell = new CacheCell(data, timeout)
        let cache = null
        // if (name.startsWith('_')) {
        try {
          uni.setStorageSync(name, cachecell)
          cache = cacheMap.set(name, cachecell)
        } catch (e) {
          console.log(e)
        }
        // } else {
        //   cache = cacheMap.set(name, cachecell)
        // }
        return cache
      }
      get(name: string) {
        return isTimeout(name) ? null : cacheMap.get(name).data
      }
      delete(name: string) {
        let value = false
        if (name.startsWith('_')) {
          try {
            uni.removeStorageSync(name)
            value = cacheMap.delete(name)
          } catch (e) {
            console.log(e)
          }
        } else {
          value = cacheMap.delete(name)
        }
        return value
      }
      has(name: string) {
        return !isTimeout(name)
      }
      clear() {
        let value = false
        try {
          uni.clearStorageSync()
          cacheMap.clear()
          value = true
        } catch (e) {
          console.log(e)
        }
        return value
      }
    }
    
    export const minCache = new MinCache()
    
    

    相关文章

      网友评论

          本文标题:uni-app 自定义缓存机制

          本文链接:https://www.haomeiwen.com/subject/ghpfqltx.html