如何利用Typescript封裝本地存儲(chǔ)
前言
本地存儲(chǔ)是前端開發(fā)過(guò)程中經(jīng)常會(huì)用到的技術(shù),但是官方api在使用上多有不便,且有些功能并沒(méi)有提供給我們相應(yīng)的api,比如設(shè)置過(guò)期時(shí)間等。本文無(wú)意于介紹關(guān)于本地存儲(chǔ)概念相關(guān)的知識(shí),旨在使用typescript封裝一個(gè)好用的本地存儲(chǔ)類。
本地存儲(chǔ)使用場(chǎng)景
- 用戶登錄后token的存儲(chǔ)
- 用戶信息的存儲(chǔ)
- 不同頁(yè)面之間的通信
- 項(xiàng)目狀態(tài)管理的持久化,如redux的持久化、vuex的持久化等
- 性能優(yōu)化等
- ...
使用中存在的問(wèn)題
- 官方api不是很友好(過(guò)于冗長(zhǎng)),且都是以字符串的形式存儲(chǔ),存取都要進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換
- localStorage.setItem(key, value)
- ...
- 無(wú)法設(shè)置過(guò)期時(shí)間
- 以明文的形式存儲(chǔ),一些相對(duì)隱私的信息用戶都能很輕松的在瀏覽器中查看到
- 同源項(xiàng)目共享本地存儲(chǔ)空間,可能會(huì)引起數(shù)據(jù)錯(cuò)亂
解決方案
將上述問(wèn)題的解決方法封裝在一個(gè)類中,通過(guò)簡(jiǎn)單接口的形式暴露給用戶直接調(diào)用。 類中將會(huì)封裝以下功能:
- 數(shù)據(jù)類型的轉(zhuǎn)換
- 過(guò)期時(shí)間
- 數(shù)據(jù)加密
- 統(tǒng)一的命名規(guī)范
功能實(shí)現(xiàn)
// 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 }
以上代碼簡(jiǎn)單的實(shí)現(xiàn)了本地存儲(chǔ)的基本功能,內(nèi)部完成了存取時(shí)的數(shù)據(jù)類型轉(zhuǎn)換操作,使用方式如下:
import { LStorage, SStorage } from './storage' ... LStorage.set('data', { name: 'zhangsan' }) LStorage.get('data') // { name: 'zhangsan' }
加入過(guò)期時(shí)間
設(shè)置過(guò)期時(shí)間的思路為:在set的時(shí)候在數(shù)據(jù)中加入expires的字段,記錄數(shù)據(jù)存儲(chǔ)的時(shí)間,get的時(shí)候?qū)⑷〕龅膃xpires與當(dāng)前時(shí)間進(jìn)行比較,如果當(dāng)前時(shí)間大于expires,則表示已經(jīng)過(guò)期,此時(shí)清除該數(shù)據(jù)記錄,并返回null,expires類型可以是boolean類型和number類型,默認(rèn)為false,即不設(shè)置過(guò)期時(shí)間,當(dāng)用戶設(shè)置為true時(shí),默認(rèn)過(guò)期時(shí)間為1年,當(dāng)用戶設(shè)置為具體的數(shù)值時(shí),則過(guò)期時(shí)間為用戶設(shè)置的數(shù)值,代碼實(shí)現(xiàn)如下:
interface IStoredItem { value: any expires?: number } ... set( key: string, value: any, expires: boolean | number = false, ) { const source: IStoredItem = { value: null } if (expires) { // 默認(rèn)設(shè)置過(guò)期時(shí)間為1年,這個(gè)可以根據(jù)實(shí)際情況進(jìn)行調(diào)整 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 } }
加入數(shù)據(jù)加密
加密用到了crypto-js包,在類中封裝encrypt,decrypt兩個(gè)私有方法來(lái)處理數(shù)據(jù)的加密和解密,當(dāng)然,用戶也可以通過(guò)encryption字段設(shè)置是否對(duì)數(shù)據(jù)進(jìn)行加密,默認(rèn)為true,即默認(rèn)是有加密的。另外可通過(guò)process.env.NODE_ENV獲取當(dāng)前的環(huán)境,如果是開發(fā)環(huán)境則不予加密,以方便開發(fā)調(diào)試,代碼實(shí)現(xiàn)如下:
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 } } }
加入命名規(guī)范
可以通過(guò)在key前面加上一個(gè)前綴來(lái)規(guī)范命名,如項(xiàng)目名_版本號(hào)_key類型的合成key,這個(gè)命名規(guī)范可自由設(shè)定,可以通過(guò)一個(gè)常量設(shè)置,也可以通過(guò)獲取package.json中的name和version進(jìn)行拼接,代碼實(shí)現(xiàn)如下:
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 }
總結(jié)
到此這篇關(guān)于如何利用Typescript封裝本地存儲(chǔ)的文章就介紹到這了,更多相關(guān)Typescript封裝本地存儲(chǔ)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用JavaScript實(shí)現(xiàn)一個(gè)炫酷的羅盤時(shí)鐘
在探究前端動(dòng)畫時(shí),想到之前在鎖屏壁紙看到的羅盤時(shí)鐘,看著很是炫酷,于是說(shuō)干就干,下面就跟隨小編一起來(lái)學(xué)習(xí)一下如何使用JS實(shí)現(xiàn)一個(gè)炫酷的羅盤時(shí)鐘效果吧2024-02-02解決layui動(dòng)態(tài)添加的元素click等事件觸發(fā)不了的問(wèn)題
今天小編就為大家分享一篇解決layui動(dòng)態(tài)添加的元素click等事件觸發(fā)不了的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-09-09JS函數(shù)參數(shù)的傳遞與同名參數(shù)實(shí)例分析
這篇文章主要介紹了JS函數(shù)參數(shù)的傳遞與同名參數(shù),結(jié)合實(shí)例形式分析了JS函數(shù)參數(shù)的傳遞與同名參數(shù)相關(guān)原理、使用技巧與操作注意事項(xiàng),需要的朋友可以參考下2020-03-03該如何加載google-analytics(或其他第三方)的JS
很多網(wǎng)站為了獲取用戶訪問(wèn)網(wǎng)站的統(tǒng)計(jì)信息,使用了google-analytics或其他分析網(wǎng)站(下面的討論中只提google-analytics,簡(jiǎn)稱ga)。2010-05-05extjs4圖表繪制之折線圖實(shí)現(xiàn)方法分析
這篇文章主要介紹了extjs4圖表繪制之折線圖實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了extjs4繪制折線圖的相關(guān)操作技巧、實(shí)現(xiàn)方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2020-03-03JS實(shí)現(xiàn)百度搜索框關(guān)鍵字推薦
這篇文章主要為大家詳細(xì)介紹了JS實(shí)現(xiàn)百度搜索框關(guān)鍵字推薦,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02