首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >localStorage, sessionStorage 本地缓存包装函数

localStorage, sessionStorage 本地缓存包装函数

作者头像
copy_left
发布2020-11-11 11:05:08
6070
发布2020-11-11 11:05:08
举报
文章被收录于专栏:方球方球
/**
 * 本地缓存包装函数
 * @author copy-left
 * @time 2020-11-10
 * 
 */

let registed = false 

/**
 * 本地缓存包装函数
 * 
 * @summary 
 * 为本地缓存对象 localStorage,sessionStorage 添加 setItem getItem 包装函数
 * 包装函数将原字符参数或返回值通过JSON转换为对象
 * 
 * @remind
 * 因为使用JSON对数据做转换, 数据格式必须服务json格式, 所以报错纯字符时将报错,
 * 此时可以使用原生方法
 * 
 * @example
 * import { registSaveFn } from '@micro/utils'
 * registSaveFn() //全局调用一次
 *  
 * const saveKey = 'USER'
 * localStorage.$setItem(saveKey, { name: 'copy', sex: 'man' })
 * const user = localStorage.$getItem(saveKey)
 * console.log(user.name)
 */
export function registSaveFn():void {
  if(registed){return}

  localStorage.__proto__.$setItem = buildSetItem(localStorage)
  localStorage.__proto__.$getItem = buildGetItem(localStorage)

  sessionStorage.__proto__.$setItem = buildSetItem(sessionStorage)
  sessionStorage.__proto__.$getItem = buildGetItem(sessionStorage)
  
  registed = true
}

export function buildSetItem (storage:typeof localStorage | typeof sessionStorage): <T = any>(key: string, data: T) => void {
  return <T = any>(key: string, data: T) => {
    try {
      const dataStr = JSON.stringify(data)
      storage.setItem(key, dataStr)
    } catch (error) {
      console.error(`${typeof(storage)} 设置失败: `, error)
    }
  }
}

export function buildGetItem (storage:typeof localStorage | typeof sessionStorage): <T = any>(key: string) => T | null {
  return <T = any>(key: string): T | null => {
    const dataStr = storage.getItem(key)
    try {
      return dataStr ? JSON.parse(dataStr) : null
    } catch (error) {
      console.error(`${typeof(storage)} 获取失败: `, error)
      return null
    }
  }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档