LsxCacheHelper.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { PageNode } from '../components/PageNode';
  2. export class LsxCacheHelper {
  3. /**
  4. * @private
  5. */
  6. static retrieveFromSessionStorage() {
  7. return JSON.parse(sessionStorage.getItem('lsx-cache')) || {};
  8. }
  9. /**
  10. * stringify and save obj
  11. *
  12. * @static
  13. * @param {object} cacheObj
  14. *
  15. * @memberOf LsxCacheHelper
  16. */
  17. static saveToSessionStorage(cacheObj) {
  18. sessionStorage.setItem('lsx-cache', JSON.stringify(cacheObj));
  19. }
  20. /**
  21. * generate cache key for storing to storage
  22. *
  23. * @static
  24. * @param {LsxContext} lsxContext
  25. * @returns
  26. *
  27. * @memberOf LsxCacheHelper
  28. */
  29. static generateCacheKeyFromContext(lsxContext) {
  30. return `${lsxContext.fromPagePath}__${lsxContext.lsxArgs}`;
  31. }
  32. /**
  33. *
  34. *
  35. * @static
  36. * @param {string} key
  37. * @returns
  38. *
  39. * @memberOf LsxCacheHelper
  40. */
  41. static getStateCache(key) {
  42. const cacheObj = LsxCacheHelper.retrieveFromSessionStorage();
  43. const stateCache = cacheObj[key];
  44. if (stateCache != null && stateCache.nodeTree != null) {
  45. // instanciate PageNode
  46. stateCache.nodeTree = stateCache.nodeTree.map((obj) => {
  47. return PageNode.instanciateFrom(obj);
  48. });
  49. }
  50. return stateCache;
  51. }
  52. /**
  53. * store state object of React Component with specified key
  54. *
  55. * @static
  56. * @param {string} key
  57. * @param {object} lsxState state object of React Component
  58. *
  59. * @memberOf LsxCacheHelper
  60. */
  61. static cacheState(key, lsxState) {
  62. const cacheObj = LsxCacheHelper.retrieveFromSessionStorage();
  63. cacheObj[key] = lsxState;
  64. LsxCacheHelper.saveToSessionStorage(cacheObj);
  65. }
  66. /**
  67. * clear all state caches
  68. *
  69. * @static
  70. *
  71. * @memberOf LsxCacheHelper
  72. */
  73. static clearAllStateCaches() {
  74. LsxCacheHelper.saveToSessionStorage({});
  75. }
  76. }