百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

如何让localStorage支持过期时间设置

toyiye 2024-06-21 12:42 11 浏览 0 评论

前言

最近在项目开发中,遇见了大家都常会遇见的问题,让本地存储支持过期时间的设置。那相信学习前端的童鞋们都知道,我们经常是会用的 cookielocalStoragesessionStorage,它们三个都是可以用来存放数据的。这里我们就不细讲它们之间的区别,主要讲当我们设置localStorage的时候,怎么来给它设置一个过期时间了?下来我们就开始今天的主题。

封装

根据一般的业务需求,我们需要支持`新增,修改,删除`,按照初步设想,开始编写我们代码。可跳过中间部分,直接查看最后的完整版代码示例(TS目前还有不太熟练的地方,有什么地方有问题欢迎指出)

// 定义类
class NStorage {
  storage: Storage;
  constructor(name?: string) {
    this.storage = window[name as keyof typeof window] || window.localStorage
  }
  /**
   * @description 存储方法
   * @param {String} key 键名
   * @param {any} value 值
   * @param {number} [expires] 可选,默认0,永久
   */
  set(key: string, value: any, expires: number = 0) {
    const storeValue = {
      value,
      startTime: new Date().getTime(),
      __expires__: expires
    }
    this.storage.setItem(key, JSON.stringify(storeValue))
  }
  /**
   * @description 获取方法
   * @param {String} key 键名
   * @returns {any} 值
   */
  get(key: string) {
    try {
      const storeItem = this.storage.getItem(key) || '{}'
      const storeValue = JSON.parse(storeItem)
      const time = new Date().getTime()
      // 如果是永久,则直接返回
      if (storeValue?.__expires__ === 0) return storeValue
      // 判断当前时间是否过期
      if (storeValue?.startTime && (time - storeValue?.startTime >= storeValue?.__expires__)) {
        this.remove(key);
        return null;
      }
      return storeValue.value
    } catch (error) {
      return null
    }
  }
  /**
   * @description 删除方法
   * @param {String} key 删除键名
   */
  remove(key: string) {
    key && this.storage.removeItem(key);
  }
  /**
   * @description 清除所有本地存储
   */
  clear() {
    this.storage.clear();
  }
}

下面是本地测试:

const store = new NStorage()

store.set('name', '小红', { expires: 10 })

let count = 0
const time = setInterval(() => {
  const name = store.get('name')
  console.log(name)
  count += 1

  if (count > 10) {
    clearInterval(time)
  }
}, 1000)

在控制台可以看见打印的 小红,3秒后localStorage里面的值就会被删除。功能我们是实现啦,是不是就可以皆大欢喜了?有没有bug?有没有可以优化的问题了?那当然是有的了:

1. 设置的过期时间,表示的是秒?分?小时?

2. 如果多次设置同一个值,那么依据现在逻辑,每次都会重新计算时间,但是我可能只是更新值,时间不需要重新计算了?

优化

定义出选项类型

// 定义支持时间类型,依次:年、月、日、时、分、秒
type TUnitType = 'Y' | 'M' | 'D' | 'h' | 'm' | 's'
// 定义可选参类型
interface IExtraOptions {
  expires?: number;
  unit?: TUnitType,
  reset?: boolean
}

// 设置默认初始值
const EXTRA_OPTIONS: IExtraOptions = {
  expires: 0, // 默认永久
  unit: 's', // 默认秒
  reset: false // 是否重置时间
}
// 根据单位和传入时间,计算出毫秒级时间
function calcTime(time: number, unit: TUnitType = 's') {
  let newTime = 0
  switch (unit) {
    case 'Y':
      newTime = time * 365 * 24 * 60 * 60 * 1000
      break;
    case 'M':
      // 注意??:月份这里偷懒,直接使用每月30天计算
      newTime = time * 30 * 24 * 60 * 60 * 1000
      break;
    case 'D':
      newTime = time * 24 * 60 * 60 * 1000
      break;
    case 'h':
      newTime = time * 60 * 60 * 1000
      break;
    case 'm':
      newTime = time * 60 * 1000
      break;
    case 's':
      newTime = time * 1000
      break;
    default:
      newTime = time
      break;
  }
  return newTime
}


**修改 set、get 方法**

  /**
   * @description 存储方法
   * @param {String} key 键名
   * @param {any} value 值
   * @param {number} [options] 可选
   * @param {Number} [options.expires] 默认0,永久
   * @param {String} [options.unit] 默认's',秒
   * @param {Boolean} [options.reset] 默认false,不重置
   */
  set(key: string, value: any, options?: IExtraOptions) {
  const isExist = this.hasKey(key)
  const extra = Object.assign(EXTRA_OPTIONS, options)
  if (isExist) {
    // 如果存在,判断是否是需要重新设置值
    const sValue = this.get(key, true)
    sValue.value = value
    sValue.__expires__ = calcTime(extra.expires || sValue.__expires__, extra.unit || sValue.__unit__)
    if (extra.reset) {
      // 存在且重新设置时间
      sValue.startTime = new Date().getTime()
      this._set(key, sValue)
    } else {
      // 如果已经存在,且不重新计算时间,则直接修改值后存储
      this._set(key, sValue)
    }
  } else {
    const storeValue = {
      value,
      startTime: new Date().getTime(),
      __expires__: calcTime(extra.expires as number, extra.unit),
      __unit__: extra.unit
    };
    this._set(key, storeValue)
  }
}
  /**
   * @description set内部方法
   * @param {String} key 键名
   * @param {any} value 值
   */
  private _set(key: string, value: any) {
    this.storage.setItem(key, JSON.stringify(value));
  }
  /**
   * @description 获取方法
   * @param {String} key 键名
   * @param {Boolean} [isMerge] 可选,是否获取处理后的对象
   * @returns {any} 值
   */
  get(key: string, isMerge: boolean = false) {
    try {
      // 不存在直接返回 null
      if (!key) return null
      const storeItem = this.storage.getItem(key) || '{}'
      const storeValue = JSON.parse(storeItem)
      const time = new Date().getTime()
      // 如果是永久,则直接返回
      if (storeValue?.__expires__ === 0) return isMerge ? storeValue : storeValue.value;
      // 判断当前时间是否过期,过期则删除当前存储值
      if (storeValue?.startTime && (time - storeValue?.startTime >= storeValue?.__expires__)) {
        this.remove(key);
        return null;
      }
      return isMerge ? storeValue : storeValue.value;
    } catch (error) {
      return null
    }
  }
  /**
   * @description 是否存在
   * @param {String} key 键
   * @returns {Boolean} true|false
   */
  hasKey(key: string) {
    if (!key) return false
    const value = this.get(key)
    return value ? true : false
  }

优化后使用介绍

const store = new NStorage()
// 普通设置,不过期
store.set('name', '小红')
// 设置过期时间5秒
store.set('name', '小红', { expires: 5 })
// 设置过期时间5分钟,其他更换单位即可
store.set('name', '小红', { expires: 5, unit: 'm' })
// 重新计算有效时长(就相当于在设置的时刻起,再往后延长之前的设置时间)
store.set('name', '小红', { reset: true })

// 获取值
store.get('name')

// 删除值
store.remove('name')

// 删除所有值
store.clear()

// 当前存储值中是否存在
store.hasKey('name')

完整版代码

// 定义支持时间类型,依次:年、月、日、时、分、秒
type TUnitType = 'Y' | 'M' | 'D' | 'h' | 'm' | 's'
// 定义可选参类型
interface IExtraOptions {
  expires?: number;
  unit?: TUnitType,
  reset?: boolean
}

// 设置默认初始值
const EXTRA_OPTIONS: IExtraOptions = {
  expires: 0, // 默认永久
  unit: 's', // 默认秒
  reset: false // 是否重置时间
}
// 根据单位和传入时间,计算出毫秒级时间
function calcTime(time: number, unit: TUnitType = 's') {
  let newTime = 0
  switch (unit) {
    case 'Y':
      newTime = time * 365 * 24 * 60 * 60 * 1000
      break;
    case 'M':
      // 月份这里偷懒,直接使用每月30天计算
      newTime = time * 30 * 24 * 60 * 60 * 1000
      break;
    case 'D':
      newTime = time * 24 * 60 * 60 * 1000
      break;
    case 'h':
      newTime = time * 60 * 60 * 1000
      break;
    case 'm':
      newTime = time * 60 * 1000
      break;
    case 's':
      newTime = time * 1000
      break;
    default:
      newTime = time
      break;
  }
  return newTime
}

class NStorage {
  storage: Storage;
  constructor(name?: string) {
    this.storage = window[name as keyof typeof window] || window.localStorage
  }
  /**
   * @description 存储方法
   * @param {String} key 键名
   * @param {any} value 值
   * @param {number} [options] 可选
   * @param {Number} [options.expires] 默认0,永久
   * @param {String} [options.unit] 默认's',秒
   * @param {Boolean} [options.reset] 默认false,不重置
   */
  set(key: string, value: any, options?: IExtraOptions) {
    const isExist = this.hasKey(key)
    const extra = Object.assign(EXTRA_OPTIONS, options)
    if (isExist) {
      // 如果存在,判断是否是需要重新设置值
      const sValue = this.get(key, true)
      sValue.value = value
      sValue.__expires__ = calcTime(extra.expires || sValue.__expires__, extra.unit || sValue.__unit__)
      if (extra.reset) {
        // 存在且重新设置时间
        sValue.startTime = new Date().getTime()
        this._set(key, sValue)
      } else {
        // 如果已经存在,且不重新计算时间,则直接修改值后存储
        this._set(key, sValue)
      }
    } else {
      const storeValue = {
        value,
        startTime: new Date().getTime(),
        __expires__: calcTime(extra.expires as number, extra.unit),
        __unit__: extra.unit
      };
      this._set(key, storeValue)
    }
  }
  /**
   * @description set内部方法
   * @param {String} key 键名
   * @param {any} value 值
   */
  private _set(key: string, value: any) {
    this.storage.setItem(key, JSON.stringify(value));
  }
  /**
   * @description 获取方法
   * @param {String} key 键名
   * @param {Boolean} [isMerge] 可选,是否获取处理后的对象
   * @returns {any} 值
   */
  get(key: string, isMerge: boolean = false) {
    try {
      // 不存在直接返回 null
      if (!key) return null
      const storeItem = this.storage.getItem(key) || '{}'
      const storeValue = JSON.parse(storeItem)
      const time = new Date().getTime()
      // 如果是永久,则直接返回
      if (storeValue?.__expires__ === 0) return isMerge ? storeValue : storeValue.value;
      // 判断当前时间是否过期,过期则删除当前存储值
      if (storeValue?.startTime && (time - storeValue?.startTime >= storeValue?.__expires__)) {
        this.remove(key);
        return null;
      }
      return isMerge ? storeValue : storeValue.value;
    } catch (error) {
      return null
    }
  }
  /**
   * @description 删除方法
   * @param {String} key 删除键名
   */
  remove(key: string) {
    key && this.storage.removeItem(key);
  }
  /**
   * @description 清除所有本地存储
   */
  clear() {
    this.storage.clear();
  }
  /**
   * @description 是否存在
   * @param {String} key 键
   * @returns {Boolean} true|false
   */
  hasKey(key: string) {
    if (!key) return false
    const value = this.get(key)
    return value ? true : false
  }
}

最后

里面的逻辑也可根据需求自己添加修改,代码测试我也可能存在未测到的地方,如果有问题欢迎各位大大指出!

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码