2
0

storage.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. class StorageAdapter {
  2. constructor(type) {
  3. if (type === "session") {
  4. this.storage = window.sessionStorage;
  5. }
  6. else if (type === "local") {
  7. this.storage = window.localStorage;
  8. }
  9. }
  10. setItem(key, value) {
  11. return this.storage.setItem(key, JSON.stringify(value));
  12. }
  13. getItem(key) {
  14. const item = this.storage.getItem(key);
  15. if (item) {
  16. try {
  17. return JSON.parse(item);
  18. }
  19. catch (error) {
  20. return item;
  21. }
  22. }
  23. return null;
  24. }
  25. removeItem(key) {
  26. return this.storage.removeItem(key);
  27. }
  28. getStorage() {
  29. return this.storage;
  30. }
  31. get length() {
  32. return this.storage.length;
  33. }
  34. clear() {
  35. return this.storage.clear();
  36. }
  37. key(index) {
  38. return this.storage.key(index);
  39. }
  40. }
  41. StorageAdapter.session = new StorageAdapter("session");
  42. StorageAdapter.local = new StorageAdapter("local");
  43. export { StorageAdapter };