Skip to content

Improvement for isCacheValid #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
12 changes: 10 additions & 2 deletions jquery-ajax-localstorage-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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){
Expand Down