zoukankan      html  css  js  c++  java
  • javascript本地缓存方案-- 存储对象和设置过期时间

    cz-storage 解决问题

    1. 前端js使用localStorage的时候只能存字符串,不能存储对象

    cz-storage 可以存储 object undefined number string

    2. localStorage没有过期时间

    cz-storage 可以设置以天为单位的过期时间

    3. github地址

    安装

    yarn add cz-storage || npm i cz-storage
    

    使用

    import LS from 'cz-storage'
    
    let value = {name: 'xiejun'}
    // 设值
    // put (<key>, value, expiredTime)
    // expiredTime 过期时间单位是天 1/8 === 3小时
    LS.put('key', value, 1)
    
    // 获取值
    LS.get('key')
    
    // 清楚所有缓存
    LS.clear()
    
    // 删除某个key
    LS.remove('key')
    

    源码

    /**
     * 使用 html5 提供的 localStorage来缓存数据
     **/
    const SPLIT_STR = '@'
    const localStorage = window.localStorage
    
    const DATA_PROCESS_MAPPING = {
      'number': {
        save : data => data,
        parse: data => Number.parseFloat(data)
      },
      'object': {
        save : data => JSON.stringify(data),
        parse: data => JSON.parse(data)
      },
      'undefined': {
        save: data => data,
        parse: () => undefined
      },
      'default': {
        save : data => data,
        parse: data => data
      }
    }
    
    function getProcess(type) {
      return DATA_PROCESS_MAPPING[type] || DATA_PROCESS_MAPPING['default']
    }
    
    export default {
      get(key) {
        let stringData = localStorage.getItem(key)
        if (stringData) {
          let dataArray = stringData.split('@')
          let data
          let now = Date.now()
          if (dataArray.length > 2 && dataArray[2] < now) { // 缓存过期
            localStorage.removeItem(key)
            return null
          } else {
            let value = decodeURIComponent(dataArray[1])
            data = getProcess(dataArray[0]).parse(value)
            return data
          }
        }
        return null
      },
      put(key, value, expired) { // expired 过期时间 单位天 默认是100 上线测试没问题替换旧的设值
        const type = typeof value
        const process = getProcess(type)
        if (!expired) { // 默认不传 不过期
          value = type + SPLIT_STR + encodeURIComponent(process.save(value))
        } else {
          let time = expired * 24 * 60 * 60 * 1000 + new Date().getTime()
          value = type + SPLIT_STR + process.save(value) + SPLIT_STR + time
        }
        localStorage.setItem(key, value)
      },
      clear() {
        localStorage.clear()
      },
      remove(key) {
        localStorage.removeItem(key)
      }
    }
    

    个人公众号

  • 相关阅读:
    开放API接口安全处理!
    ant笔记
    并发调试
    IDEA 设置(中文乱码、svn、热部署、ideolog 、Jrebel )
    win10家庭版升级专业版
    org.json package
    'root'@'localhost'不能登录问题
    javascript之DOM选择符
    javascript之DOM(四其他类型)
    javascript之DOM(三Element类型)
  • 原文地址:https://www.cnblogs.com/net-xiejun/p/9660510.html
Copyright © 2011-2022 走看看