Encapsulate a class that operates on local, session, cookie (batch operation)

First, let’s look at the basic operations of the three methods

  • LocalStorage: localStorage. It has the characteristics of long-term validity and does not empty data even after the browser is closed
class Storage {

    // constructor(options) { }

    constructor() {

            console.log('constructor')

        }

        // Get data for _key => {data, keyInfo}

    _getData(_key) {

            console.log('Get is called')

          let _keys = Array.isArray(_key) ? _key : [_key]

            _keys.forEach((a)= > {

                return JSON.parse(localStorage.getItem())

            });

        }

        // Remove operation

    _remove(_key) {

            let _keys = Array.isArray(_key) ? _key : [_key]

            const _data = _keys.forEach((a)= > {

                localStorage.removeItem();

            });

        }

        // Set operation

     set(key, data, options = {}) {

            console.log('Set is called')

            const _key = this._getKey(key);

            const _data = JSON.stringify(data, options);

            localStorage.setItem(_key, _data);

        }

        // Whether the validity period

    _isExpired(_key) {

        const { keyInfo } = this._getData(_key);

        const { expires, timestamp } = keyInfo;

        if(! expires) {

            return true;

        }

        return (

            timestamp + expires * 24 * 3600 * 1000 - new Date().getTime() < 0

        );

    }



}

Copy the code

Summary: Let’s take a look at what we’ve done. The first is the get operation, which determines whether the incoming data is an array, converts it to an array, and then uses forEach to retrieve the elements of the array from localstorage.getitem (). Finally, the obtained data is converted into data format through json.parse (). The removal operation also determines whether it is an array, and then removes it one by one. The setting operation is carried out in the form of key and value pairs, and the last one determines whether it is expired

  • Session: a short-term store that is deleted when the browser is closed
class Session {

    get(key) {

        let keys = Array.isArray(key) ? key : [key]

        keys.forEach((r) = > {

            return JSON.parse(sessionStorage.getItem[r])

        });

    }

    set(key, value) {

            var data = {

                value: value

            }

            sessionStorage.setItem[key] = JSON.stringify(data);

        }

        / / delete

    remove(key) {

            let keys = Array.isArray(key) ? key : [key]

            keys.forEach((r) = > {

                return JSON.parse(sessionStorage.removeItem[r])

            });

        }

        // Delete all

    clear() {

        sessionStorage.clear();

    }

}

Copy the code

Summary: It is similar to local

  • Cookie: a variable stored on a visitor’s computer. This cookie is sent every time the same computer requests a page through the browser. You can use JavaScript to create and retrieve cookie values
class Cookie {

    setCookie(name, value, n) {

        var oDate = new Date(a);

        oDate.setDate(oDate.getDate() + n);

        document.cookie = name + "=" + value + "; expires=" + oDate;

    }

    getCookie(name) {

        var str = document.cookie;

        var arr = str.split("; ");

        for (var i = 0; i < arr.length; i++) {

            //console.log(arr[i]);

            var newArr = arr[i].split("=");

            if (newArr[0] == name) {

                return newArr[1];

            }

        }

    }

    removeCookie(name) {

        this.setCookie(name, 1.- 1);

    }

}

Copy the code

Summary: This is a regular cookie operation class, the actual use of the need to adjust, the setting is a key-value pair plus time string concatenation, when obtaining, to remove the special symbols, removal is relatively simple

triad

class Storage {

    // constructor(options) { }

    constructor() {

            console.log('constructor')

        }

        // Get data for _key => {data, keyInfo}

    _getData(_key) {

            console.log('Get is called')

            let _keys = Array.isArray(_key) ? _key : [_key]

            _keys.forEach((a)= > {

                return JSON.parse(localStorage.getItem())

            });

        }

        // Remove operation

    _remove(_key) {

            let _keys = Array.isArray(_key) ? _key : [_key]

            _keys.forEach((a)= > {

                localStorage.removeItem();

            });

        }

        // Set operation

    set(key, data, options = {}) {

            console.log('Set is called')

            const _key = this._getKey(key);

            const _data = JSON.stringify(data, options);

            localStorage.setItem(_key, _data);

        }

        // Whether the validity period

    _isExpired(_key) {

        const { keyInfo } = this._getData(_key);

        const { expires, timestamp } = keyInfo;

        if(! expires) {

            return true;

        }

        return (

            timestamp + expires * 24 * 3600 * 1000 - new Date().getTime() < 0

        );

    }



}

class Cookie {

    setCookie(name, value, n) {

        var oDate = new Date(a);

        oDate.setDate(oDate.getDate() + n);

        document.cookie = name + "=" + value + "; expires=" + oDate;

    }

    getCookie(name) {

        var str = document.cookie;

        var arr = str.split("; ");

        for (var i = 0; i < arr.length; i++) {

            //console.log(arr[i]);

            var newArr = arr[i].split("=");

            if (newArr[0] == name) {

                return newArr[1];

            }

        }

    }

    removeCookie(name) {

        this.setCookie(name, 1.- 1);

    }

}

class Session {

    get(key) {

        let keys = Array.isArray(key) ? key : [key]

        keys.forEach((r) = > {

            return JSON.parse(sessionStorage[r])

        });

    }

    set(key, value) {

            var data = {

                value: value

            }

            sessionStorage[key] = JSON.stringify(data);

        }

        / / delete

    remove(key) {

            let keys = Array.isArray(key) ? key : [key]

            keys.forEach((r) = > {

                return JSON.parse(sessionStorage.removeItem[r])

            });

        }

        // Delete all

    clear() {

        sessionStorage.clear();

    }

}

export { Storage, Cookie, Session };

Copy the code

So to summarize, let’s put them in a file, let’s expose their class names, and let’s see how we use them, okay

  const local = new _Storage()

  local.set("name", { name"SuperIron" }, { expires1 });

  const Info = local.get('name')

Copy the code

First we instantiate the class and pass the parameters according to the reserved slots