網站首頁 前端文檔 正文
前言
本地存儲是前端開發過程中經常會用到的技術,但是官方api在使用上多有不便,且有些功能并沒有提供給我們相應的api,比如設置過期時間等。本文無意于介紹關于本地存儲概念相關的知識,旨在使用typescript封裝一個好用的本地存儲類。
本地存儲使用場景
- 用戶登錄后token的存儲
- 用戶信息的存儲
- 不同頁面之間的通信
- 項目狀態管理的持久化,如redux的持久化、vuex的持久化等
- 性能優化等
- ...
使用中存在的問題
- 官方api不是很友好(過于冗長),且都是以字符串的形式存儲,存取都要進行數據類型轉換
- localStorage.setItem(key, value)
- ...
- 無法設置過期時間
- 以明文的形式存儲,一些相對隱私的信息用戶都能很輕松的在瀏覽器中查看到
- 同源項目共享本地存儲空間,可能會引起數據錯亂
解決方案
將上述問題的解決方法封裝在一個類中,通過簡單接口的形式暴露給用戶直接調用。 類中將會封裝以下功能:
- 數據類型的轉換
- 過期時間
- 數據加密
- 統一的命名規范
功能實現
// 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獲取當前的環境,如果是開發環境則不予加密,以方便開發調試,代碼實現如下:
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 }
總結
原文鏈接:https://juejin.cn/post/7048976403349536776
相關推薦
- 2022-10-07 C語言實現動態版通訊錄的示例代碼_C 語言
- 2024-03-04 JQ實現將div的滾動條滾動到指定子元素所在的位置
- 2023-12-23 React環境安裝配置
- 2022-05-03 python實現跨進程(跨py文件)通信示例_python
- 2022-07-09 Python如何保留float類型小數點后3位_python
- 2022-12-06 .net程序開發IOC控制反轉和DI依賴注入詳解_ASP.NET
- 2022-11-03 通過VS下載的NuGet包修改其下載存放路徑的操作方法_python
- 2022-10-17 .Net?Core使用Coravel實現任務調度的完整步驟_實用技巧
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支