DroopyTersen
9/19/2016 - 7:10 PM

Supports localStorage or sessionStorage. Supports optional expiration. Supports regex key cache clearing

Supports localStorage or sessionStorage. Supports optional expiration. Supports regex key cache clearing

var storage = localStorage;
var cache = {};

cache.setStorageType = function(localOrSessionStorage) {
    storage = localOrSessionStorage
}

var _isExpired = function(cacheValue) {
    return (cacheValue.expiration) && ((new Date()).getTime() > cacheValue.expiration);
};

cache.get = function(key) {
	var valueStr = storage.getItem(key);
	if (valueStr) {
		var val = JSON.parse(valueStr);
		return !_isExpired(val) ? val.payload : null
	}

	return null;
};

// takes in optional 'expires' which is a millisecond duration
cache.set = function(key, payload, expires) {
	var value = { payload: payload };
    if (expires) {
        value.expiration = (new Date()).getTime() + expires;
    }
    storage.setItem(key, JSON.stringify(value));
    return payload;
};

var _getAllKeys = function() {
	var keys = [];
	for ( var i = 0, len = storage.length; i < len; ++i ) {
		keys.push(storage.key(i));
	}
	return keys;
};

cache.clear = function(keyOrFilterFunc) {
	if (!keyOrFilterFunc) throw new Error("You must pass a key or a filter function");
	if (typeof keyOrFilterFunc === "string") {
		storage.removeItem(keyOrFilterFunc);
	} else {
		_getAllKeys()
			.filter(keyOrFilterFunc)
			.forEach(function(key) {
				storage.removeItem(key);
			})
	}
};

module.exports = cache;