基于 TypeScript 封装增强型本地存储:支持过期、加密与命名规范

作者:异步漫步时间:2026-10-24 21:34:51浏览:428

本文介绍如何使用 TypeScript 封装一个功能增强的本地存储类,解决原生 API 的不足。通过封装,实现了自动数据类型转换、支持设置过期时间、数据加密以及统一的命名规范。该类适用于 Token 存储、用户信息持久化及状态管理同步等场景,并提供简洁的接口供前端项目直接调用。

前言

在前端开发中,本地存储是一项常用技术。然而,官方提供的 API 在使用上存在诸多不便,且部分功能(如设置过期时间)并未直接提供。本文不赘述本地存储的基础概念,而是重点展示如何使用 TypeScript 封装一个实用且功能完善的本地存储类。

本地存储使用场景

  • 用户登录后 token 的存储
  • 用户信息的存储
  • 不同页面之间的通信
  • 项目状态管理的持久化,如 redux 的持久化、vuex 的持久化等
  • 性能优化等
  • ...

使用中存在的问题

  • 官方API不够友好(过于冗长),且仅以字符串形式存储,存取时需进行数据类型转换
    • 官方 api 不是很友好(过于冗长),且都是以字符串的形式存储,存取都要进行数据类型转换
    • ...
  • 无法设置过期时间
  • 以明文的形式存储,一些相对隐私的信息用户都能很轻松的在浏览器中查看到
  • 同源项目共享本地存储空间,可能会引起数据错乱

解决方案

针对上述问题,我们将解决方案封装在一个类中,通过简洁的接口暴露给用户直接调用。该类将封装以下核心功能:

  • 数据类型的转换
  • 过期时间
  • 数据加密
  • 统一的命名规范

功能实现

// storage.ts

enum StorageType {
  l = 'localStorage',
  s = 'sessionStorage'
}

class MyStorage {
  storage: Storage

  constructor(type: StorageType) {
    this.storage = type === StorageType.l ? window.localStorage : window.sessionStorage
  }

  set(
    key: string,
    value: any
  ) {
    const data = JSON.stringify(value)
    this.storage.setItem(key, data)
  }

  get(key: string) {
    const value = this.storage.getItem(key)
    if (value) {
      return JSON.parse(value)
  }

  delete(key: string) {
    this.storage.removeItem(key)
  }

  clear() {
    this.storage.clear()
  }
}

const LStorage = new MyStorage(StorageType.l)
const SStorage = new MyStorage(StorageType.s)

export { LStorage, SStorage }

上述代码初步实现了本地存储的基本存取功能,并在内部完成了存取时的数据类型转换操作。具体使用方式如下:

import { LStorage, SStorage } from './storage'

...

LStorage.set('data', { name: 'zhangsan' })
LStorage.get('data') // { name: 'zhangsan' }

加入过期时间

设置过期时间的核心思路是:在 set 操作时,在数据对象中增加 expires 字段,记录数据存储的时间戳;在 get 操作时,将取出的 expires 值与当前时间进行比较。若当前时间大于 expires,则判定数据已过期,此时清除该条数据记录并返回 null。expires 参数类型支持 boolean 或 number,默认为 false(即不设置过期时间)。当用户设置为 true 时,默认过期时间设为 1 年;若用户指定具体数值,则过期时间为该数值。代码实现如下:

interface IStoredItem {
  value: any
  expires?: number
}
...
set(
    key: string,
    value: any,
    expires: boolean | number = false,
  ) {
    const source: IStoredItem = { value: null }
    if (expires) {
    // 默认设置过期时间为1年,这个可以根据实际情况进行调整
      source.expires =
        new Date().getTime() +
        (expires === true ? 1000 * 60 * 60 * 24 * 365 : expires)
    }
    source.value = value
    const data = JSON.stringify(source)
    this.storage.setItem(key, data)
  }
  
  get(key: string) {
    const value = this.storage.getItem(key)
    if (value) {
      const source: IStoredItem = JSON.parse(value)
      const expires = source.expires
      const now = new Date().getTime()
      if (expires && now > expires) {
        this.delete(key)
        return null
      }

      return source.value
    }
  }

加入数据加密

加密功能依赖于 crypto-js 包。在类中封装了 encrypt 和 decrypt 两个私有方法,分别用于处理数据的加密和解密。用户可以通过 encryption 字段配置是否对数据进行加密,默认值为 true(即默认开启加密)。此外,代码通过 process.env.NODE_ENV 获取当前运行环境,若为开发环境(development),则不进行加密处理,以便于调试。代码实现如下:

import CryptoJS from 'crypto-js'

const SECRET_KEY = 'nkldsx@#45#VDss9'
const IS_DEV = process.env.NODE_ENV === 'development'
...
class MyStorage {
  ...
  
  private encrypt(data: string) {
    return CryptoJS.AES.encrypt(data, SECRET_KEY).toString()
  }

  private decrypt(data: string) {
    const bytes = CryptoJS.AES.decrypt(data, SECRET_KEY)
    return bytes.toString(CryptoJS.enc.Utf8)
  }
  
  set(
    key: string,
    value: any,
    expires: boolean | number = false,
    encryption = true
  ) {
    const source: IStoredItem = { value: null }
    if (expires) {
      source.expires =
        new Date().getTime() +
        (expires === true ? 1000 * 60 * 60 * 24 * 365 : expires)
    }
    source.value = value
    const data = JSON.stringify(source)
    this.storage.setItem(key, IS_DEV ? data : encryption ? this.encrypt(data) : data
    )
  }
  
  get(key: string, encryption = true) {
    const value = this.storage.getItem(key)
    if (value) {
      const source: IStoredItem = JSON.parse(value)
      const expires = source.expires
      const now = new Date().getTime()
      if (expires && now > expires) {
        this.delete(key)
        return null
      }

      return IS_DEV
        ? source.value
        : encryption
        ? this.decrypt(source.value)
        : source.value
    }
  }
  
}

加入命名规范

可以通过在 key 前添加前缀来规范命名,例如采用“项目名_版本号_key”的格式合成 key。该命名规范可自由设定,既可以通过常量手动设置,也可以动态获取 package.json 中的 name 和 version 字段进行拼接。代码实现如下:

const config = require('../../package.json')

const PREFIX = config.name + '_' + config.version + '_'

...
class MyStorage {

  // 合成key
  private synthesisKey(key: string) {
    return PREFIX + key
  }
  
  ...
  
 set(
    key: string,
    value: any,
    expires: boolean | number = false,
    encryption = true
  ) {
    ...
    this.storage.setItem(
      this.synthesisKey(key),
      IS_DEV ? data : encryption ? this.encrypt(data) : data
    )
  }
  
  get(key: string, encryption = true) {
    const value = this.storage.getItem(this.synthesisKey(key))
    ...
  }

}

完整代码

import CryptoJS from 'crypto-js'
const config = require('../../package.json')

enum StorageType {
  l = 'localStorage',
  s = 'sessionStorage'
}

interface IStoredItem {
  value: any
  expires?: number
}

const SECRET_KEY = 'nkldsx@#45#VDss9'
const PREFIX = config.name + '_' + config.version + '_'
const IS_DEV = process.env.NODE_ENV === 'development'

class MyStorage {
  storage: Storage

  constructor(type: StorageType) {
    this.storage =
      type === StorageType.l ? window.localStorage : window.sessionStorage
  }

  private encrypt(data: string) {
    return CryptoJS.AES.encrypt(data, SECRET_KEY).toString()
  }

  private decrypt(data: string) {
    const bytes = CryptoJS.AES.decrypt(data, SECRET_KEY)
    return bytes.toString(CryptoJS.enc.Utf8)
  }

  private synthesisKey(key: string) {
    return PREFIX + key
  }

  set(
    key: string,
    value: any,
    expires: boolean | number = false,
    encryption = true
  ) {
    const source: IStoredItem = { value: null }
    if (expires) {
      source.expires =
        new Date().getTime() +
        (expires === true ? 1000 * 60 * 60 * 24 * 365 : expires)
    }
    source.value = value
    const data = JSON.stringify(source)
    this.storage.setItem(
      this.synthesisKey(key),
      IS_DEV ? data : encryption ? this.encrypt(data) : data
    )
  }

  get(key: string, encryption = true) {
    const value = this.storage.getItem(this.synthesisKey(key))
    if (value) {
      const source: IStoredItem = JSON.parse(value)
      const expires = source.expires
      const now = new Date().getTime()
      if (expires && now > expires) {
        this.delete(key)
        return null
      }

      return IS_DEV
        ? source.value
        : encryption
        ? this.decrypt(source.value)
        : source.value
    }
  }

  delete(key: string) {
    this.storage.removeItem(this.synthesisKey(key))
  }

  clear() {
    this.storage.clear()
  }
}

const LStorage = new MyStorage(StorageType.l)
const SStorage = new MyStorage(StorageType.s)

export { LStorage, SStorage }

总结

到此这篇关于如何利用 Typescript 封装本地存储的文章就介绍到这了,更多相关 Typescript 封装本地存储内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

作者最新文章
相关文章
更多