Lightweight plug-in sdstorage is used to operate localStorage to support expiration, batch search and deletion, etc.

Keywords: JSON Database

Preface

In order to facilitate processing, most of the data operations are completed in the front end, and saved to the database only when the interface is finally saved. In order to ensure that the data is still maintained when the interface is unexpectedly closed and reopened, it is necessary to save the data locally. Originally, cookie s are used. Considering that the size of data is limited (4k), local Storage has to be used instead. Storage does not support expiration and has to write a plug-in to meet the requirements.

Plugin source code

/*!
 * Copyright (C) Corporation. All rights reserved.
 *
 * Author      :  lihaitao
 * Email        : lhtzbj12@126.com
 * Create Date  : 2017-10-18
 * Description  : localstorage Operating tools, support for expiration processing, Key batch deletion expired, etc.
 * Version      : V1.0.0
 *
 * Revision History:
 *      Date         Author               Description
 *      2017-10-18   lihaitao             Complete the first version
 *
 */
var sdstorage = function () {
    var lstorage = window.localStorage;

    //How long does it take to save the incoming key data to expire by default?
    function save(dkey, data, expires) {
        if (!lstorage) return false;
        expires = calculateExpiration(expires);
        var expiretime = 0; //not overdue
        if (expires) {
            expiretime = expires;
        }
        var obj = {sdata: data, exp: expiretime};
        //Preservation
        try {
            lstorage[dkey] = JSON.stringify(obj);
            return true;
        }
        catch (e) {
            console.error(e);
            return false;
        }
        return false;
    }

    //Get expired or nonexistent returns''
    function get(dkey) {
        if (!lstorage) return '';
        var str = lstorage[dkey];
        if (str) {
            try {
                var obj = JSON.parse(str);
                //Judge whether it is overdue
                var now = new Date().getTime();
                if (obj.exp && (obj.exp === 0 || obj.exp > now)) {
                    //Console. log ('key:'+ dkey +', and'+ (obj.exp - now) / 1000 + seconds' before expiration);
                    return obj.sdata;
                } else {
                    //Delete when expired
                    remove(dkey);
                }
            } catch (e) {
                console.error(e);
                return '';
            }
        }
        return '';
    }

    //Clear all, and if you drop before entering, only those that drop before prefix are cleared
    function clear(prefix) {
        if (!lstorage) return;
        if (prefix) {
            for (var i = 0; i < lstorage.length; i++) {
                var key = lstorage.key(i);
                //If prefix has value, only the same pre-drop is processed
                if (key.indexOf(prefix) === 0) {
                    lstorage.removeItem(key);
                }
            }
        } else {
            lstorage.clear();
        }
    }

    //Delete single
    function remove(dkey) {
        if (!lstorage) return;
        lstorage.removeItem(dkey);
    }

    //Clear out expired data, drop in key, and divide by prefix only data that has expired
    function removeexp(prefix) {
        if (!lstorage) return;
        for (var i = 0; i < lstorage.length; i++) {
            var key = lstorage.key(i);
            //If prefix has value, only the same pre-drop is processed
            if (!prefix || key.indexOf(prefix) === 0) {
                get(key);
            }
            //console.log(key);
        }
    }

    //Check whether the browser supports
    function test() {
        if (lstorage) {
            return true;
        } else {
            return false
        }
    }

    //Calculate expiration time
    var calculateExpiration = function (cookieExpire) {
        if (cookieExpire === null || typeof cookieExpire === 'undefined') {
            return null;
        }
        var time = cookieExpire.replace(/[0-9]*/, ''); //s,mi,h,d,m,y
        cookieExpire = cookieExpire.replace(/[A-Za-z]{1,2}/, ''); //number
        switch (time.toLowerCase()) {
            case 's':
                cookieExpire = cookieExpire;
                break;
            case 'mi':
                cookieExpire = cookieExpire * 60;
                break;
            case 'h':
                cookieExpire = cookieExpire * 60 * 60;
                break;
            case 'd':
                cookieExpire = cookieExpire * 24 * 60 * 60;
                break;
            case 'm':
                cookieExpire = cookieExpire * 30 * 24 * 60 * 60;
                break;
            case 'y':
                cookieExpire = cookieExpire * 365 * 24 * 60 * 60;
                break;
            default:
                cookieExpire = cookieExpire;
                break;
        }
        var d = new Date().getTime();
        cookieExpire = d + cookieExpire * 1000;
        return cookieExpire;
    };

    return {
        //Check for support
        test: test,
        //How long does it expire to save the incoming key data, default expiration, unit s (seconds) mi (minutes) h (hours) D (days) m (months) y (years)
        //Successfully return true, or false
        save: save,
        //Get, nonexistent or expired return''
        get: get,
        //Delete by key
        remove: remove,
        //Delete expired incoming key s before dropping out, dividing by prefix only data that has expired
        removeexp: removeexp,
        //Clean up all if you drop in before entering, only those that drop out before prefix are cleared
        clear: clear,
    };
}();

Method

test

Role: Determine whether the browser supports it or not, and return true false

sdstorage.test()

save

Function: Save data and return true false
Parametric 1: key of data
Parameter 2: Data, only str is supported. If JSON is used, JSON.stringify() is used to convert to a string.
Parameter 3: Validity period, unit s (seconds) mi (minutes) h (hours) D (days) m (months) y (years), no value passed, no expiration

var key = 'users_info';
var data={'username':'lhtzbj12'};
sdstorage.save(key,JSON.stringify(data),'2d');//Validity period: 2 days

get

Function: Get data, if data returns after expiration, and delete
Parametric 1: key of data

var key = 'users_info';
var str = sdstorage.get(key);

remove

Role: Delete data
Parametric 1: key of data

var key = 'users_info';
sdstorage.remove(key);

removeexp

Function: Delete expired data
Parametric 1: Data key drops forward and deletes all expired data without passing values

var prefix = 'users_';
sdstorage.removeexp(prefix);//Delete all key expired data starting with'users_'
sdstorage.removeexp();//Delete all expired data

clear

Function: Delete some data
Parametric 1: Data key drops forward and deletes all data without passing values

var prefix = 'users_';
sdstorage.clear(prefix);//Delete all key s starting with'users_'
sdstorage.clear();//Delete all data

Posted by d-Pixie on Sat, 06 Apr 2019 15:12:30 -0700