CacheUtils.js 1.8 KB

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