storage.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import {
  2. LOCAL_STORAGE_KEYS,
  3. SESSION_STORAGE_KEYS,
  4. } from "src/constants/storage";
  5. import { isAfter } from "date-fns";
  6. interface StorageData {
  7. cache?: string;
  8. data: any;
  9. }
  10. class StorageTool<T extends "local" | "session"> {
  11. storage: Storage;
  12. constructor(storageType: "local" | "session" = "local") {
  13. this.storage =
  14. storageType === "local" ? window.localStorage : window.sessionStorage;
  15. }
  16. get(key: T extends "local" ? LOCAL_STORAGE_KEYS : SESSION_STORAGE_KEYS) {
  17. const value = this.storage.getItem(key as string);
  18. try {
  19. const data: StorageData = value ? JSON.parse(value) : value;
  20. if (data !== null) {
  21. if (data.cache) {
  22. if (isAfter(new Date(data.cache), Date.now())) {
  23. return data.data;
  24. }
  25. this.remove(key);
  26. return null;
  27. }
  28. return data.data;
  29. }
  30. return data;
  31. } catch (error) {
  32. return value;
  33. }
  34. }
  35. set(
  36. key: T extends "local" ? LOCAL_STORAGE_KEYS : SESSION_STORAGE_KEYS,
  37. data: any,
  38. option?: { expires: string | Date }
  39. ) {
  40. let cache: string | Date = "";
  41. if (option?.expires) {
  42. try {
  43. cache = new Date(option.expires);
  44. } catch (error) {
  45. console.warn(`set storage ${key} expires error`);
  46. }
  47. }
  48. return this.storage.setItem(key as string, JSON.stringify({ data, cache }));
  49. }
  50. remove(key: T extends "local" ? LOCAL_STORAGE_KEYS : SESSION_STORAGE_KEYS) {
  51. return this.storage.removeItem(key as string);
  52. }
  53. clear() {
  54. return this.storage.clear();
  55. }
  56. }
  57. export const localStorageTool = new StorageTool<"local">("local");
  58. export const sessionStorageTool = new StorageTool<"session">("session");