你還在直接用 localStorage 麼?該提升下逼格了

很多人在用 localStorage 或 sessionStorage 的時候喜歡直接用,明文存儲,直接將信息暴露在;瀏覽器中,雖然一般場景下都能應付得了且簡單粗暴,但特殊需求情況下,比如設置定時功能,就不能實現。就需要對其進行二次封裝,爲了在使用上增加些安全感,那加密也必然是少不了的了。爲方便項目使用,特對常規操作進行封裝。不完善之處會進一步更新...(更新於:2022.06.02 16:30)

設計

封裝之前先梳理下所需功能,並要做成什麼樣,採用什麼樣的規範,部分主要代碼片段是以 localStorage作爲示例,最後會貼出完整代碼的。可以結合項目自行優化,也可以直接使用。

// 區分存儲類型 type
// 自定義名稱前綴 prefix
// 支持設置過期時間 expire
// 支持加密可選,開發環境下未方便調試可關閉加密

// 支持數據加密 這裏採用 crypto-js 加密 也可使用其他方式

// 判斷是否支持 Storage isSupportStorage

// 設置 setStorage

// 獲取 getStorage

// 是否存在 hasStorage

// 獲取所有key getStorageKeys

// 根據索引獲取key getStorageForIndex

// 獲取localStorage長度 getStorageLength

// 獲取全部 getAllStorage

// 刪除 removeStorage

// 清空 clearStorage

//定義參數 類型 window.localStorage,window.sessionStorage,
const config = {
    type: 'localStorage', // 本地存儲類型 localStorage/sessionStorage
    prefix: 'SDF_0.0.1', // 名稱前綴 建議:項目名 + 項目版本
    expire: 1, //過期時間 單位:秒
    isEncrypt: true // 默認加密 爲了調試方便, 開發過程中可以不加密
}
複製代碼

設置 setStorage

Storage 本身是不支持過期時間設置的,要支持設置過期時間,可以效仿 Cookie 的做法,setStorage(key,value,expire) 方法,接收三個參數,第三個參數就是設置過期時間的,用相對時間,單位秒,要對所傳參數進行類型檢查。可以設置統一的過期時間,也可以對單個值得過期時間進行單獨配置。兩種方式按需配置。

代碼實現:

// 設置 setStorage
export const setStorage = (key,value,expire=0) ={
    if (value === '' || value === null || value === undefined) {
        value = null;
    }

    if (isNaN(expire) || expire < 1) throw new Error("Expire must be a number");

    expire = (expire?expire:config.expire) * 60000;
    let data = {
        value: value, // 存儲值
        time: Date.now(), //存值時間戳
        expire: expire // 過期時間
    }

    window[config.type].setItem(key, JSON.stringify(data));
}
複製代碼

獲取 getStorage

首先要對 key 是否存在進行判斷,防止獲取不存在的值而報錯。對獲取方法進一步擴展,只要在有效期內獲取 Storage 值,就對過期時間進行續期,如果過期則直接刪除該值。並返回 null

// 獲取 getStorage
export const getStorage = (key) ={
    // key 不存在判斷
    if (!window[config.type].getItem(key) || JSON.stringify(window[config.type].getItem(key)) === 'null'){
        return null;
    }

    // 優化 持續使用中續期
    const storage = JSON.parse(window[config.type].getItem(key));
    console.log(storage)
    let nowTime = Date.now();
    console.log(config.expire*6000 ,(nowTime - storage.time))
    // 過期刪除
    if (storage.expire && config.expire*6000 < (nowTime - storage.time)) {
        removeStorage(key);
        return null;
    } else {
        // 未過期期間被調用 則自動續期 進行保活
        setStorage(key,storage.value);
        return storage.value;
    }
}
複製代碼

獲取所有值

// 獲取全部 getAllStorage
export const getAllStorage = () ={
    let len = window[config.type].length // 獲取長度
    let arr = new Array() // 定義數據集
    for (let i = 0; i < len; i++) {
        // 獲取key 索引從0開始
        let getKey = window[config.type].key(i)
        // 獲取key對應的值
        let getVal = window[config.type].getItem(getKey)
        // 放進數組
        arr[i] = { 'key': getKey, 'val': getVal, }
    }
    return arr
}
複製代碼

刪除 removeStorage

// 名稱前自動添加前綴
const autoAddPrefix = (key) ={
    const prefix = config.prefix ? config.prefix + '_' : '';
    return  prefix + key;
}

// 刪除 removeStorage
export const removeStorage = (key) ={
    window[config.type].removeItem(autoAddPrefix(key));
}
複製代碼

清空 clearStorage

// 清空 clearStorage
export const clearStorage = () ={
    window[config.type].clear();
}
複製代碼

加密、解密

加密採用的是 crypto-js

// 安裝crypto-js
npm install crypto-js

// 引入 crypto-js 有以下兩種方式
import CryptoJS from "crypto-js";
// 或者
const CryptoJS = require("crypto-js");
複製代碼

對 crypto-js 設置密鑰和密鑰偏移量, 可以採用將一個私鑰經 MD5 加密生成 16 位密鑰獲得。

// 十六位十六進制數作爲密鑰
const SECRET_KEY = CryptoJS.enc.Utf8.parse("3333e6e143439161");
// 十六位十六進制數作爲密鑰偏移量
const SECRET_IV = CryptoJS.enc.Utf8.parse("e3bbe7e3ba84431a");
複製代碼

對加密方法進行封裝

/**
 * 加密方法
 * @param data
 * @returns {string}
 */
export function encrypt(data) {
  if (typeof data === "object") {
    try {
      data = JSON.stringify(data);
    } catch (error) {
      console.log("encrypt error:", error);
    }
  }
  const dataHex = CryptoJS.enc.Utf8.parse(data);
  const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
    iv: SECRET_IV,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.ciphertext.toString();
}
複製代碼

對解密方法進行封裝

/**
 * 解密方法
 * @param data
 * @returns {string}
 */
export function decrypt(data) {
  const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
  const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
    iv: SECRET_IV,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}
複製代碼

在存儲數據及獲取數據中進行使用:

這裏我們主要看下進行加密和解密部分,部分方法在下面代碼段中並未展示,請注意,不能直接運行。

const config = {
    type: 'localStorage', // 本地存儲類型 sessionStorage
    prefix: 'SDF_0.0.1', // 名稱前綴 建議:項目名 + 項目版本
    expire: 1, //過期時間 單位:秒
    isEncrypt: true // 默認加密 爲了調試方便, 開發過程中可以不加密
}

// 設置 setStorage
export const setStorage = (key, value, expire = 0) ={
    if (value === '' || value === null || value === undefined) {
        value = null;
    }

    if (isNaN(expire) || expire < 0) throw new Error("Expire must be a number");

    expire = (expire ? expire : config.expire) * 1000;
    let data = {
        value: value, // 存儲值
        time: Date.now(), //存值時間戳
        expire: expire // 過期時間
    }
    // 對存儲數據進行加密 加密爲可選配置
    const encryptString = config.isEncrypt ? encrypt(JSON.stringify(data)): JSON.stringify(data);
    window[config.type].setItem(autoAddPrefix(key), encryptString);
}

// 獲取 getStorage
export const getStorage = (key) ={
    key = autoAddPrefix(key);
    // key 不存在判斷
    if (!window[config.type].getItem(key) || JSON.stringify(window[config.type].getItem(key)) === 'null') {
        return null;
    }

    // 對存儲數據進行解密
    const storage = config.isEncrypt ? JSON.parse(decrypt(window[config.type].getItem(key))) : JSON.parse(window[config.type].getItem(key));
    let nowTime = Date.now();
    
    // 過期刪除
    if (storage.expire && config.expire * 6000 < (nowTime - storage.time)) {
        removeStorage(key);
        return null;
    } else {
        //  持續使用時會自動續期
        setStorage(autoRemovePrefix(key), storage.value);
        return storage.value;
    }
}
複製代碼

使用

使用的時候你可以通過 import 按需引入,也可以掛載到全局上使用,一般建議少用全局方式或全局變量,爲後來接手項目繼續開發維護的人,追查代碼留條便捷之路!不要爲了封裝而封裝,儘可能基於項目需求和後續的通用,以及使用上的便捷。比如獲取全部存儲變量,如果你項目上都未曾用到過,倒不如刪減掉,留着過年也不見得有多香,不如爲減小體積做點貢獻!

import {isSupportStorage, hasStorage, setStorage,getStorage,getStorageKeys,getStorageForIndex,getStorageLength,removeStorage,getStorageAll,clearStorage} from '@/utils/storage'
複製代碼

完整代碼

該代碼已進一步完善,需要的可以直接進一步優化,也可以將可優化或可擴展的建議,留言說明,我會進一步迭代的。可以根據自己的需要刪除一些不用的方法,以減小文件大小。

/***
 * title: storage.js
 * Author: Gaby
 * Email: xxx@126.com
 * Time: 2022/6/1 17:30
 * last: 2022/6/2 17:30
 * Desc: 對存儲的簡單封裝
 */
 
import CryptoJS from 'crypto-js';

// 十六位十六進制數作爲密鑰
const SECRET_KEY = CryptoJS.enc.Utf8.parse("3333e6e143439161");
// 十六位十六進制數作爲密鑰偏移量
const SECRET_IV = CryptoJS.enc.Utf8.parse("e3bbe7e3ba84431a");

// 類型 window.localStorage,window.sessionStorage,
const config = {
    type: 'localStorage', // 本地存儲類型 sessionStorage
    prefix: 'SDF_0.0.1', // 名稱前綴 建議:項目名 + 項目版本
    expire: 1, //過期時間 單位:秒
    isEncrypt: true // 默認加密 爲了調試方便, 開發過程中可以不加密
}

// 判斷是否支持 Storage
export const isSupportStorage = () ={
    return (typeof (Storage) !== "undefined") ? true : false
}

// 設置 setStorage
export const setStorage = (key, value, expire = 0) ={
    if (value === '' || value === null || value === undefined) {
        value = null;
    }

    if (isNaN(expire) || expire < 0) throw new Error("Expire must be a number");

    expire = (expire ? expire : config.expire) * 1000;
    let data = {
        value: value, // 存儲值
        time: Date.now(), //存值時間戳
        expire: expire // 過期時間
    }
    
    const encryptString = config.isEncrypt 
    ? encrypt(JSON.stringify(data))
    : JSON.stringify(data);
    
    window[config.type].setItem(autoAddPrefix(key), encryptString);
}

// 獲取 getStorage
export const getStorage = (key) ={
    key = autoAddPrefix(key);
    // key 不存在判斷
    if (!window[config.type].getItem(key) || JSON.stringify(window[config.type].getItem(key)) === 'null') {
        return null;
    }

    // 優化 持續使用中續期
    const storage = config.isEncrypt 
    ? JSON.parse(decrypt(window[config.type].getItem(key))) 
    : JSON.parse(window[config.type].getItem(key));
    
    let nowTime = Date.now();

    // 過期刪除
    if (storage.expire && config.expire * 6000 < (nowTime - storage.time)) {
        removeStorage(key);
        return null;
    } else {
        // 未過期期間被調用 則自動續期 進行保活
        setStorage(autoRemovePrefix(key), storage.value);
        return storage.value;
    }
}

// 是否存在 hasStorage
export const hasStorage = (key) ={
    key = autoAddPrefix(key);
    let arr = getStorageAll().filter((item)=>{
        return item.key === key;
    })
    return arr.length ? true : false;
}

// 獲取所有key
export const getStorageKeys = () ={
    let items = getStorageAll()
    let keys = []
    for (let index = 0; index < items.length; index++) {
        keys.push(items[index].key)
    }
    return keys
}

// 根據索引獲取key
export const getStorageForIndex = (index) ={
    return window[config.type].key(index)
}

// 獲取localStorage長度
export const getStorageLength = () ={
    return window[config.type].length
}

// 獲取全部 getAllStorage
export const getStorageAll = () ={
    let len = window[config.type].length // 獲取長度
    let arr = new Array() // 定義數據集
    for (let i = 0; i < len; i++) {
        // 獲取key 索引從0開始
        let getKey = window[config.type].key(i)
        // 獲取key對應的值
        let getVal = window[config.type].getItem(getKey)
        // 放進數組
        arr[i] = {'key': getKey, 'val': getVal,}
    }
    return arr
}

// 刪除 removeStorage
export const removeStorage = (key) ={
    window[config.type].removeItem(autoAddPrefix(key));
}

// 清空 clearStorage
export const clearStorage = () ={
    window[config.type].clear();
}

// 名稱前自動添加前綴
const autoAddPrefix = (key) ={
    const prefix = config.prefix ? config.prefix + '_' : '';
    return  prefix + key;
}

// 移除已添加的前綴
const autoRemovePrefix = (key) ={
    const len = config.prefix ? config.prefix.length+1 : '';
    return key.substr(len)
    // const prefix = config.prefix ? config.prefix + '_' : '';
    // return  prefix + key;
}

/**
 * 加密方法
 * @param data
 * @returns {string}
 */
const encrypt = (data) ={
    if (typeof data === "object") {
        try {
            data = JSON.stringify(data);
        } catch (error) {
            console.log("encrypt error:", error);
        }
    }
    const dataHex = CryptoJS.enc.Utf8.parse(data);
    const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
        iv: SECRET_IV,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString();
}

/**
 * 解密方法
 * @param data
 * @returns {string}
 */
const decrypt = (data) ={
    const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
    const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
        iv: SECRET_IV,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}
複製代碼

關於本文

來自:Gaby

https://juejin.cn/post/7104301566857445412

前端瓶子君 瓶子君,致力於幫助前端開啓技術專項 + 算法之路!

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/KD6ZQOcoLm2PWfVxHSSVWQ