前端:兼容 cookie 和 localStorage 类,且可设置过期时限

前言

兼容 CookielocalStorage 两种方式,且都可设置过期时限;

初始化

init(type, timeOut)

参数

名称 类型 描述
type String 存储方式。支持 2 种类型:cookie(存储值最大为 4KB)、localStorage(存储值最大为 5M)
timeOut Number 过期时限。单位为小时,例如 7 * 24 为 7 天

返回

Booleantrue 表示初始化成功,false 表示已初始化;

示例

初始化方法 Storage.init ,仅第一次生效;

// 初始化为 localStorage 类型,7 天过期
Storage.init('localStorage', 7 * 24);

方法

set(key, val)

  • 保存;
  • 返回:无;
  • 参数如下:
名称 类型 描述
key String 唯一标识
val Object 存储值

get(key)

  • 获取;
  • 返回:被存储的值,过期为 null
  • 参数如下:
名称 类型 描述
key String 唯一标识

remove(key)

  • 移除;
  • 返回:Booleantrue 成功,false 失败;
  • 参数如下:
名称 类型 描述
key String 唯一标识

exist(key)

  • 判断对象是否存在;
  • 返回:Booleantrue 存在,false 过期或移除;
  • 参数如下:
名称 类型 描述
key String 唯一标识

clear()

  • 清空全部;
  • 返回:无;
  • 参数:无;

示例

此处使用 Vue2.x




真正的实现

文件 Storage.js,文件分三部分 MyCookieMyLocalStorageStorage

// 唯一key
const MY_KEYS = '_My_Storage_Keys'

class MyCookie {

    constructor() {
        this.keys = [MY_KEYS]
        this.lastTime = null
        let flag = false
        let name = `${MY_KEYS}=`
        let ca = document.cookie.split(';')
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i].trim()
            if (c.indexOf(name) == 0)
                flag = true
        }
        this.keys = flag ? this.get(MY_KEYS) : []

    }

    getKeys() {
        return this.keys
    }

    setHistory(timeOut) {
        timeOut = timeOut || this.lastTime
        let d = new Date()
        d.setTime(d.getTime() + (timeOut * 60 * 60 * 1000))
        let expires = 'expires=' + d.toGMTString()
        document.cookie = `${MY_KEYS}=` + JSON.stringify({ data: this.keys }) + '; ' + expires
        this.lastTime = timeOut
    }

    set(key, val, timeOut) {
        let d = new Date()
        d.setTime(d.getTime() + (timeOut * 60 * 60 * 1000))
        let expires = 'expires=' + d.toGMTString()
        document.cookie = key + '=' + JSON.stringify({ data: val }) + '; ' + expires
        this.keys.indexOf(key) < 0 && this.keys.push(key) && this.setHistory(timeOut)
    }

    get(key) {
        if (!this.exist(key))
            return null

        let name = key + '='
        let ca = document.cookie.split(';')
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i].trim()
            if (c.indexOf(name) === 0)
                return JSON.parse(c.substring(name.length, c.length)).data
        }
    }

    remove(key) {
        for (let i in this.keys) {
            if (key == this.keys[i]) {
                document.cookie = this.keys[i] + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
                this.keys.splice(i, 1)
                this.setHistory()
                return true
            }
        }
        return false
    }

    exist(key) {
        let name = key + '='
        let ca = document.cookie.split(';')
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i].trim()
            if (c.indexOf(name) === 0)
                return true
        }
        this.remove(key)
        return this.keys.indexOf(key) > -1
    }

    clear() {
        for (let i in this.keys) {
            document.cookie = this.keys[i] + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
        }
        this.keys = [MY_KEYS]
        this.setHistory(0)
    }
}

class MyLocalStorage {

    constructor() {
        this.keys = [MY_KEYS];
        this.keys = localStorage.getItem(MY_KEYS) ? this.get(MY_KEYS) : [];
        for (let i in this.keys) {
            this.exist(this.keys[i]);
        }
    }

    getKeys() {
        return this.keys;
    }

    setHistory() {
        localStorage.setItem(MY_KEYS, JSON.stringify({ data: this.keys })) //转换成json字符串序列
    }

    set(key, val, timeOut) {
        let cur = new Date().getTime()
        localStorage.setItem(key, JSON.stringify({ data: val, time: cur, timeOut: timeOut })) //转换成json字符串序列
        this.keys.indexOf(key) < 0 && this.keys.push(key) && this.setHistory()
    }

    get(key) {
        if (!this.exist(key))
            return null

        let val = localStorage.getItem(key) //获取存储的元素
        let dataObj = JSON.parse(val) //解析出json对象
        if (dataObj.timeOut != null && (new Date().getTime() - dataObj.time > dataObj.timeOut * 60 * 60 * 1000)) //如果当前时间-减去存储的元素在创建时候设置的时间 > 过期时间
        {
            return null
        } else {
            return dataObj.data
        }
    }

    remove(key) {
        for (let i in this.keys) {
            if (key == this.keys[i]) {
                localStorage.removeItem(this.keys[i])
                this.keys.splice(i, 1)
                this.setHistory()
                return true
            }
        }
        return false
    }

    exist(key) {
        let val = localStorage.getItem(key) //获取存储的元素
        let dataObj = JSON.parse(val) //解析出json对象
        if (dataObj && dataObj.timeOut != null && (new Date().getTime() - dataObj.time > dataObj.timeOut * 60 * 60 * 1000)) //如果当前时间-减去存储的元素在创建时候设置的时间 > 过期时间
        {
            this.remove(key)
        }
        return this.keys.indexOf(key) > -1
    }

    clear() {
        for (let i in this.keys) {
            localStorage.removeItem(this.keys[i])
        }
        this.keys = [MY_KEYS]
        this.setHistory()
    }
}

class Storage {

    static init(type, timeOut) {
        // 仅初始化一次
        if (this.currentStorage) {
            return false;
        }

        this.type = type;
        this.timeOut = timeOut;
        this.storageFactory = {
            cookie: MyCookie,
            localStorage: MyLocalStorage,
        }
        this.currentStorage = new this.storageFactory[type]();

        return true;
    }

    static getKeys() {
        return this.currentStorage.getKeys()
    }

    static set(key, val) {
        this.currentStorage.set(`_My_Storage_${key}`, val, this.timeOut)
    }

    static get(key) {
        return this.currentStorage.get(`_My_Storage_${key}`);
    }

    static remove(key) {
        return this.currentStorage.remove(`_My_Storage_${key}`);
    }

    static exist(key) {
        return this.currentStorage.exist(`_My_Storage_${key}`);
    }

    static clear() {
        this.currentStorage.clear();
    }

}

export default Storage

你可能感兴趣的:(Javascript,小知识点,前端)