第十一章:創(chuàng)建本地緩存對(duì)象

創(chuàng)建 src/utils/Storage.ts 文件

/**
 * 創(chuàng)建本地緩存對(duì)象
 * @param {string} prefixKey 鍵的前綴
 * @param {Storage} storage 緩存的類(lèi)型;可以是 localStorage 和 sessionStorage; 默認(rèn): localStorage;
 */
export const createStorage = (prefixKey: string = '', storage: Storage = localStorage) => {
    // 本地緩存類(lèi)
    const Storage = class {
        private storage = storage
        private prefixKey?: string = prefixKey

        /**
         * @description 獲取緩存的鍵
         * @param {string} key 緩存鍵
         * @return {string} 緩存的鍵
         */
        private getKey(key: string) {
            return `${this.prefixKey}${key}`.toUpperCase()
        }

        /**
         * @description 設(shè)置緩存
         * @param {string} key 緩存鍵
         * @param {any} value 緩存值
         * @param { number | null} expire 緩存有效期,單位: s;
         */
        set(key: string, value: any, expire: number | null = null) {
            const stringData = JSON.stringify({
                value,
                expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
            })
            this.storage.setItem(this.getKey(key), stringData)
        }

        /**
         * 讀取緩存
         * @param {string} key 緩存鍵
         * @param {any} defaultValue 默認(rèn)值, 當(dāng)從本地讀取不到值時(shí),返回此默認(rèn)值;默認(rèn): null;
         */
        get<T = any>(key: string, defaultValue: any = null): T | null {
            const item = this.storage.getItem(this.getKey(key))
            if (item) {
                try {
                    const data = JSON.parse(item)
                    const { value, expire } = data
                    // 在有效期內(nèi)直接返回
                    if (expire === null || expire >= Date.now()) {
                        return value
                    }
                    this.remove(this.getKey(key))
                } catch (e) {
                    console.error(e)
                    return defaultValue
                }
            }
            return defaultValue
        }

        /**
         * 從緩存刪除某項(xiàng)
         * @param {string} key 緩存鍵
         */
        remove(key: string) {
            this.storage.removeItem(this.getKey(key))
        }

        /**
         * 清空所有緩存
         */
        clear(): void {
            this.storage.clear()
        }

        /**
         * 設(shè)置cookie
         * @param {string} name cookie 名稱(chēng)
         * @param {*} value cookie 值
         * @param {number=} expire 過(guò)期時(shí)間
         * 如果過(guò)期時(shí)間為設(shè)置,默認(rèn)關(guān)閉瀏覽器自動(dòng)刪除
         */
        setCookie(name: string, value: any, expire: number | null = null) {
            document.cookie = `${this.getKey(name)}=${value}; Max-Age=${expire}`
        }

        /**
         * 根據(jù)名字獲取 cookie 值
         * @param {string} name cookie 名稱(chēng)
         */
        getCookie(name: string): string {
            const cookieArr = document.cookie.split('; ')
            for (let i = 0, length = cookieArr.length; i < length; i++) {
                const kv = cookieArr[i].split('=')
                if (kv[0] === this.getKey(name)) {
                    return kv[1]
                }
            }
            return ''
        }

        /**
         * 根據(jù)名字刪除指定的 cookie
         * @param {string} key 緩存鍵
         */
        removeCookie(key: string) {
            this.setCookie(key, 1, -1)
        }

        /**
         * 清空cookie,使所有cookie失效
         */
        clearCookie(): void {
            const keys = document.cookie.match(/[^ =;]+(?==)/g)
            if (keys) {
                for (let i = keys.length; i--;) {
                    document.cookie = `${keys[i]}=0;expire=${new Date(0).toUTCString()}`
                }
            }
        }
    }

    // 返回一個(gè)實(shí)例化后的本地緩存類(lèi)
    return new Storage()
}

export const Storage = createStorage()

export default Storage
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容