My intent is to use this object to cache data from web responses. The cache object should only be valid for the current data.
var myCache = {
Cache: { Date: '', Data: [] },
AddData: function(Name, Data){
myCache.CheckCache();
myCache.Cache.Data[Name] = Data;
},
GetData: function(Name){
myCache.CheckCache();
return myCache.Cache.Data[Name];
},
HasData: function(Name){
myCache.CheckCache();
var data = myCache.Cache.Data[Name];
var val = true;
if(typeof data === "undefined" || data == null || data === '') {
val = false;
}
return val;
},
CheckCache: function(){
var currentDate = myCache.GetCurrentDate();
var CacheDate = myCache.Cache.Date;
if(CacheDate != currentDate){
console.log('Reset Cache');
myCache.Cache.Data = [];
myCache.Cache.Date = currentDate;
}
},
GetCurrentDate: function(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if(dd < 10) {
dd = '0' + dd;
}
if(mm < 10) {
mm = '0' + mm;
}
var returnDate = yyyy + '-' + mm + '-' + dd;
return returnDate;
}
};
When the main page loads I call
myCache.CheckCache();
When I get data in the application I use the cache object as
var data;
if(myCache.HasData('UserData')){
data = myCache.GetData('UserData');
} else{
data = myWebApi.Get(Url);
}
Is there a better way of creating a cache object? Or any suggestions of improvment