为编程爱好者分享易语言教程源码的资源网
好用的代理IP,游戏必备 ____广告位招租____ 服务器99/年 ____广告位招租____ ____广告位招租____ 挂机,建站服务器
好用的代理IP,游戏必备 ____广告位招租____ 服务器低至38/年 ____广告位招租____ ____广告位招租____ 挂机,建站服务器

网站首页 > 网络编程 正文

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

三叶资源网 2022-09-28 20:18:50 网络编程 188 ℃ 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
  }
}

最后

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

Tags:

来源:三叶资源网,欢迎分享,公众号:iisanye,(三叶资源网⑤群:21414575

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

百度站内搜索
关注微信公众号
三叶资源网⑤群:三叶资源网⑤群

网站分类
随机tag
翻译工具进程保护socks5自动更新源码实时监控条形码黑客数字雨留言板填表源码界面UI微信hook限制未授权U盘枚举IE插件水印自动下载界面引擎登录注册实现桌面小精灵拖放对象模块flash动画强行兼容高DPI
最新评论