localstorage-manager.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. let _instance = null;
  2. export class LocalStorageManager {
  3. static getInstance() {
  4. if (_instance == null) {
  5. _instance = new LocalStorageManager();
  6. }
  7. return _instance;
  8. }
  9. /**
  10. * retrieve and return parsed JSON object
  11. * @param {string} namespace
  12. * @param {string} key
  13. * @returns {object}
  14. */
  15. retrieveFromSessionStorage(namespace, key) {
  16. const item = JSON.parse(sessionStorage.getItem(namespace)) || {};
  17. if (key != null) {
  18. return item[key];
  19. }
  20. return item;
  21. }
  22. /**
  23. * save JavaScript object as stringified JSON object
  24. *
  25. * @param {string} namespace
  26. * @param {string | object} cacheObjOrKey cache object or key (if third param is undefined)
  27. * @param {object} cacheObj
  28. */
  29. saveToSessionStorage(namespace, cacheObjOrKey, cacheObj) {
  30. let item = JSON.parse(sessionStorage.getItem(namespace)) || {};
  31. if (cacheObj !== undefined) {
  32. const key = cacheObjOrKey;
  33. item[key] = cacheObj;
  34. }
  35. else {
  36. item = cacheObjOrKey;
  37. }
  38. sessionStorage.setItem(namespace, JSON.stringify(item));
  39. }
  40. /**
  41. * clear all state caches
  42. *
  43. * @param {string} namespace
  44. */
  45. clearAllStateCaches(namespace) {
  46. sessionStorage.removeItem(namespace);
  47. }
  48. }