storage.ts 1020 B

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