From 6f9f3b7c9edee8487436af25ff2f4420e15ca311 Mon Sep 17 00:00:00 2001 From: Brandon Hansen Date: Fri, 7 Nov 2014 16:22:34 -0800 Subject: [PATCH 1/3] Update readme to include fetch --- README.md | 11 ++++++ lscache.js | 25 ++++++++++++ lscache.min.js | 2 +- tests/tests-cjs.js | 96 +++++++++++++++++++++++++++++++++++++++++++++- tests/tests.js | 67 ++++++++++++++++++++++++++++++++ 5 files changed, 198 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6ff6a1e..a906241 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,17 @@ Retrieves specified value from localStorage, if not expired. * * * +### lscache.fetch +Retrieves specified value from localStorage if exists. If key cannot be found runs callback function and inserts result in to cache. +#### Arguments +1. `key` (**string**) +2. `val` (**function**|**Object**|**string**) +3. `time` (**number: optional**) +#### Returns +**string | Object** : The stored value. + +* * * + ### lscache.remove Removes a value from localStorage. #### Arguments diff --git a/lscache.js b/lscache.js index ccfe11c..9c901d9 100644 --- a/lscache.js +++ b/lscache.js @@ -263,6 +263,31 @@ } }, + /** + * Attempts to get a key from localStorage cache. + * If the get request returns null (the key has not been set) + * then the callback is run and the result is stored + * @param {string} key + * @param {function|string|object} val + * @param {number} time + */ + fetch: function(key, val, time) { + var retrieveCache = this.get(key), + newCacheValue = val; + + if(retrieveCache){ + return retrieveCache; + } + + if(val instanceof Function){ + newCacheValue = val(); + } + + this.set(key, newCacheValue); + + return newCacheValue; + }, + /** * Removes a value from localStorage. * Equivalent to 'delete' in memcache, but that's a keyword in JS. diff --git a/lscache.min.js b/lscache.min.js index 53bffe7..3aa63a9 100644 --- a/lscache.min.js +++ b/lscache.min.js @@ -1 +1 @@ -!function(a,b){"function"==typeof define&&define.amd?define([],b):"undefined"!=typeof module&&module.exports?module.exports=b():a.lscache=b()}(this,function(){function a(){var a="__lscachetest__",c=a;if(void 0!==j)return j;try{g(a,c),h(a),j=!0}catch(d){j=b(d)?!0:!1}return j}function b(a){return a&&"QUOTA_EXCEEDED_ERR"===a.name||"NS_ERROR_DOM_QUOTA_REACHED"===a.name||"QuotaExceededError"===a.name?!0:!1}function c(){return void 0===k&&(k=null!=window.JSON),k}function d(a){return a+m}function e(){return Math.floor((new Date).getTime()/o)}function f(a){return localStorage.getItem(l+q+a)}function g(a,b){localStorage.removeItem(l+q+a),localStorage.setItem(l+q+a,b)}function h(a){localStorage.removeItem(l+q+a)}function i(a,b){r&&"console"in window&&"function"==typeof window.console.warn&&(window.console.warn("lscache - "+a),b&&window.console.warn("lscache - The error was: "+b.message))}var j,k,l="lscache-",m="-cacheexpiration",n=10,o=6e4,p=Math.floor(864e13/o),q="",r=!1,s={set:function(j,k,o){if(a()){if("string"!=typeof k){if(!c())return;try{k=JSON.stringify(k)}catch(r){return}}try{g(j,k)}catch(r){if(!b(r))return void i("Could not add item with key '"+j+"'",r);for(var s,t=[],u=0;u0;)s=t.pop(),i("Cache is full, removing item with key '"+j+"'"),h(s.key),h(d(s.key)),y-=s.size;try{g(j,k)}catch(r){return void i("Could not add item with key '"+j+"', perhaps it's too big?",r)}}o?g(d(j),(e()+o).toString(n)):h(d(j))}},get:function(b){if(!a())return null;var g=d(b),i=f(g);if(i){var j=parseInt(i,n);if(e()>=j)return h(b),h(g),null}var k=f(b);if(!k||!c())return k;try{return JSON.parse(k)}catch(l){return k}},remove:function(b){return a()?(h(b),void h(d(b))):null},supported:function(){return a()},flush:function(){if(a())for(var b=localStorage.length-1;b>=0;--b){var c=localStorage.key(b);0===c.indexOf(l+q)&&localStorage.removeItem(c)}},setBucket:function(a){q=a},resetBucket:function(){q=""},enableWarnings:function(a){r=a}};return s}); \ No newline at end of file +!function(a,b){"function"==typeof define&&define.amd?define([],b):"undefined"!=typeof module&&module.exports?module.exports=b():a.lscache=b()}(this,function(){function a(){var a="__lscachetest__",c=a;if(void 0!==j)return j;try{g(a,c),h(a),j=!0}catch(d){j=b(d)?!0:!1}return j}function b(a){return a&&"QUOTA_EXCEEDED_ERR"===a.name||"NS_ERROR_DOM_QUOTA_REACHED"===a.name||"QuotaExceededError"===a.name?!0:!1}function c(){return void 0===k&&(k=null!=window.JSON),k}function d(a){return a+m}function e(){return Math.floor((new Date).getTime()/o)}function f(a){return localStorage.getItem(l+q+a)}function g(a,b){localStorage.removeItem(l+q+a),localStorage.setItem(l+q+a,b)}function h(a){localStorage.removeItem(l+q+a)}function i(a,b){r&&"console"in window&&"function"==typeof window.console.warn&&(window.console.warn("lscache - "+a),b&&window.console.warn("lscache - The error was: "+b.message))}var j,k,l="lscache-",m="-cacheexpiration",n=10,o=6e4,p=Math.floor(864e13/o),q="",r=!1,s={set:function(j,k,o){if(a()){if("string"!=typeof k){if(!c())return;try{k=JSON.stringify(k)}catch(r){return}}try{g(j,k)}catch(r){if(!b(r))return void i("Could not add item with key '"+j+"'",r);for(var s,t=[],u=0;u0;)s=t.pop(),i("Cache is full, removing item with key '"+j+"'"),h(s.key),h(d(s.key)),y-=s.size;try{g(j,k)}catch(r){return void i("Could not add item with key '"+j+"', perhaps it's too big?",r)}}o?g(d(j),(e()+o).toString(n)):h(d(j))}},get:function(b){if(!a())return null;var g=d(b),i=f(g);if(i){var j=parseInt(i,n);if(e()>=j)return h(b),h(g),null}var k=f(b);if(!k||!c())return k;try{return JSON.parse(k)}catch(l){return k}},fetch:function(a,b){var c=this.get(a),d=b;return c?c:(b instanceof Function&&(d=b()),this.set(a,d),d)},remove:function(b){return a()?(h(b),void h(d(b))):null},supported:function(){return a()},flush:function(){if(a())for(var b=localStorage.length-1;b>=0;--b){var c=localStorage.key(b);0===c.indexOf(l+q)&&localStorage.removeItem(c)}},setBucket:function(a){q=a},resetBucket:function(){q=""},enableWarnings:function(a){r=a}};return s}); \ No newline at end of file diff --git a/tests/tests-cjs.js b/tests/tests-cjs.js index b966b48..449960f 100644 --- a/tests/tests-cjs.js +++ b/tests/tests-cjs.js @@ -264,6 +264,31 @@ require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof requ } }, + /** + * Attempts to get a key from localStorage cache. + * If the get request returns null (the key has not been set) + * then the callback is run and the result is stored + * @param {string} key + * @param {function|string|object} val + * @param {number} time + */ + fetch: function(key, val, time) { + var retrieveCache = this.get(key), + newCacheValue = val; + + if(retrieveCache){ + return retrieveCache; + } + + if(val instanceof Function){ + newCacheValue = val(); + } + + this.set(key, newCacheValue); + + return newCacheValue; + }, + /** * Removes a value from localStorage. * Equivalent to 'delete' in memcache, but that's a keyword in JS. @@ -326,6 +351,8 @@ require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof requ return lscache; })); +},{}],"qunit":[function(require,module,exports){ +module.exports=require('nCxwBE'); },{}],"nCxwBE":[function(require,module,exports){ (function (global){ (function browserifyShim(module, exports, define, browserify_shim__define__module__export__) { @@ -1946,8 +1973,6 @@ QUnit.diff = (function() { }).call(global, undefined, undefined, undefined, function defineExport(ex) { module.exports = ex; }); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],"qunit":[function(require,module,exports){ -module.exports=require('nCxwBE'); },{}],4:[function(require,module,exports){ /* jshint undef:true, browser:true, node:true */ /* global QUnit, test, equal, asyncTest, start, define */ @@ -2120,6 +2145,73 @@ var startTests = function (lscache) { equal(lscache.get(currentKey), longString, 'We expect value to be set'); }); + // The fetch method will allow us to insert a key in if nothing is found + // Test fetch when data already inserted + test('Testing fetch() with key already inserted', function(){ + localStorage.clear(); + var key = 'cache-key', + value = 'original-value', + newValue = 'new-value', + bucket = 'my-bucket'; + + lscache.setBucket(bucket); + lscache.set(key, value); + + var fetchResponse = lscache.fetch(key, function(){ + return newValue; + }); + + equal(fetchResponse, value, 'Expects fetch to return key when set'); + }); + + test('Testing fetch() without key inserted', function(){ + localStorage.clear(); + var key = 'cache-key', + value = 'new-value', + bucket = 'my-bucket'; + + lscache.setBucket(bucket); + + var fetchResponse = lscache.fetch(key, function(){ + return value; + }); + + equal(fetchResponse, value, 'Expects fetch to return key when set'); + }); + + + test('Testing get() after fetch() inserts new data with function callback', function(){ + localStorage.clear(); + var key = 'cache-key', + value = 'new-value', + bucket = 'my-bucket'; + + lscache.setBucket(bucket); + + var fetchResponse = lscache.fetch(key, function(){ + return value; + }); + + var getResponse = lscache.get(key); + + equal(getResponse, value, 'Expects fetch to save the result of the callback function to the key'); + }); + + test('Testing get() after fetch() inserts new data from string', function(){ + localStorage.clear(); + var key = 'cache-key', + value = 'new-value', + bucket = 'my-bucket'; + + lscache.setBucket(bucket); + + var fetchResponse = lscache.fetch(key, value); + var getResponse = lscache.get(key); + + equal(getResponse, value, 'Expects fetch to save the result of the callback function to the key'); + }); + + // We do this test last since it must wait 1 minute asyncTest('Testing set() and get() with string and expiration', 1, function() { diff --git a/tests/tests.js b/tests/tests.js index 2849751..1bc0944 100644 --- a/tests/tests.js +++ b/tests/tests.js @@ -169,6 +169,73 @@ var startTests = function (lscache) { equal(lscache.get(currentKey), longString, 'We expect value to be set'); }); + // The fetch method will allow us to insert a key in if nothing is found + // Test fetch when data already inserted + test('Testing fetch() with key already inserted', function(){ + localStorage.clear(); + var key = 'cache-key', + value = 'original-value', + newValue = 'new-value', + bucket = 'my-bucket'; + + lscache.setBucket(bucket); + lscache.set(key, value); + + var fetchResponse = lscache.fetch(key, function(){ + return newValue; + }); + + equal(fetchResponse, value, 'Expects fetch to return key when set'); + }); + + test('Testing fetch() without key inserted', function(){ + localStorage.clear(); + var key = 'cache-key', + value = 'new-value', + bucket = 'my-bucket'; + + lscache.setBucket(bucket); + + var fetchResponse = lscache.fetch(key, function(){ + return value; + }); + + equal(fetchResponse, value, 'Expects fetch to return key when set'); + }); + + + test('Testing get() after fetch() inserts new data with function callback', function(){ + localStorage.clear(); + var key = 'cache-key', + value = 'new-value', + bucket = 'my-bucket'; + + lscache.setBucket(bucket); + + var fetchResponse = lscache.fetch(key, function(){ + return value; + }); + + var getResponse = lscache.get(key); + + equal(getResponse, value, 'Expects fetch to save the result of the callback function to the key'); + }); + + test('Testing get() after fetch() inserts new data from string', function(){ + localStorage.clear(); + var key = 'cache-key', + value = 'new-value', + bucket = 'my-bucket'; + + lscache.setBucket(bucket); + + var fetchResponse = lscache.fetch(key, value); + var getResponse = lscache.get(key); + + equal(getResponse, value, 'Expects fetch to save the result of the callback function to the key'); + }); + + // We do this test last since it must wait 1 minute asyncTest('Testing set() and get() with string and expiration', 1, function() { From fe7b5eec56df3bc2e2a8397be84f811308e1329f Mon Sep 17 00:00:00 2001 From: Brandon Hansen Date: Fri, 7 Nov 2014 16:25:25 -0800 Subject: [PATCH 2/3] Update version number. --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 288f833..b7ba9ae 100755 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ }, "homepage": "http://github.com/pamelafox/lscache", "main": "lscache", - "version": "1.0.4", + "version": "1.0.5", "devDependencies": { "grunt": "~0.4.1", "grunt-cli": "~0.1.13", From ac2b091ccbadbb717bbc6f12e81b97e1bcd418b2 Mon Sep 17 00:00:00 2001 From: Brandon Hansen Date: Fri, 7 Nov 2014 16:27:26 -0800 Subject: [PATCH 3/3] Update bower version number as well --- bower.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bower.json b/bower.json index daade0a..93234b1 100755 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "lscache", - "version": "1.0.4", + "version": "1.0.5", "homepage": "https://github.com/pamelafox/lscache", "main": ["lscache.min.js", "lscache.js"], "ignore": [