CacheUtils.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. export default class Cache {
  2. static buildFullKey(key){
  3. key="jme-"+key+"-cache";
  4. return key;
  5. }
  6. static get(key){
  7. const cacheExpiration=86400000;
  8. try{
  9. key=this.buildFullKey(key);
  10. let item=localStorage.getItem(key);
  11. if(!item) throw key+" not cached!";
  12. item=JSON.parse(item);
  13. if(!item.date|| (Date.now()-item.date )>cacheExpiration) throw key+" expired!";
  14. return item.content;
  15. }catch(e){
  16. console.warn(e);
  17. return undefined;
  18. }
  19. }
  20. static cachedCycle(id,min,max,time){
  21. const key="cycle-"+id;
  22. let data=this.get(key);
  23. if(!data||data.min!=min||data.max!=max){
  24. console.warn("Invalidate cache",id);
  25. data={
  26. time:0,
  27. min:min,
  28. max:max,
  29. value:-1
  30. };
  31. }
  32. if(Date.now()-data.time>time){
  33. console.warn("Cache exceed the time limit",time);
  34. data.time=Date.now();
  35. data.value++;
  36. if(data.value>max)data.value=min;
  37. }
  38. this.set(key,data);
  39. return data.value;
  40. }
  41. static set(key,value){
  42. try{
  43. key=this.buildFullKey(key);
  44. localStorage.setItem(key,JSON.stringify({
  45. date: Date.now(),
  46. content:value
  47. }));
  48. }catch(e){
  49. console.warn(e);
  50. }
  51. }
  52. }