From 4f4c688b90c00429cd7f42c81aa5b5fde28f3d58 Mon Sep 17 00:00:00 2001 From: Dmitry Shkoliar Date: Tue, 31 Jul 2018 12:12:49 +0300 Subject: [PATCH 1/2] Improvement for isCacheValid Passes cached value to isCacheValid function to have ability to cehck validity based on cached data. --- jquery-ajax-localstorage-cache.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/jquery-ajax-localstorage-cache.js b/jquery-ajax-localstorage-cache.js index 85d2350..88c5c86 100644 --- a/jquery-ajax-localstorage-cache.js +++ b/jquery-ajax-localstorage-cache.js @@ -83,13 +83,22 @@ responseValid = options.isResponseValid, thenResponse = options.thenResponse || null, ttl, + dataType, value; if (!storage) return; ttl = storage.getItem(cacheKey + 'cachettl'); - if (cacheValid && typeof cacheValid === 'function' && !cacheValid()){ + value = storage.getItem(cacheKey); + + if (value){ + dataType = options.dataType || storage.getItem(cacheKey + 'dataType') || 'text'; + if (dataType.toLowerCase().indexOf('json') !== -1) value = JSON.parse(value); + } + + if (cacheValid && typeof cacheValid === 'function' && !cacheValid(value)){ removeFromStorage(storage, cacheKey); + value = null; ttl = 0; } @@ -98,7 +107,6 @@ ttl = 0; } - value = storage.getItem(cacheKey); if (!value){ // If value not in the cache, add a then block to request to store the results on success. jqXHR.then(thenResponse).then(function(data, status, jqXHR){ From 4ed11757592b1ea6b1e699b4d2bbbea97b4eb021 Mon Sep 17 00:00:00 2001 From: Dmitry Shkoliar Date: Tue, 31 Jul 2018 12:15:55 +0300 Subject: [PATCH 2/2] Readme update Update of readme file for isCacheValid changes. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 33a144e..1b3967e 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,8 @@ $.ajax({ cacheTTL: 1, // Optional. In hours. Can be used with float to indicate part of an hour, e.g. 0.5. cacheKey: 'post', // optional. - isCacheValid: function () { // optional. - return true; + isCacheValid: function (data) { // optional. + return data && data.code === '0'; }, isResponseValid: function (data, status, jqXHR) { // optional. return data.code === '0';