12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- import {
- LOCAL_STORAGE_KEYS,
- SESSION_STORAGE_KEYS,
- } from "src/constants/storage";
- import { isAfter } from "date-fns";
- interface StorageData {
- cache?: string;
- data: any;
- }
- class StorageTool<T extends "local" | "session"> {
- storage: Storage;
- constructor(storageType: "local" | "session" = "local") {
- this.storage =
- storageType === "local" ? window.localStorage : window.sessionStorage;
- }
- get(key: T extends "local" ? LOCAL_STORAGE_KEYS : SESSION_STORAGE_KEYS) {
- const value = this.storage.getItem(key as string);
- try {
- const data: StorageData = value ? JSON.parse(value) : value;
- if (data !== null) {
- if (data.cache) {
- if (isAfter(new Date(data.cache), Date.now())) {
- return data.data;
- }
- this.remove(key);
- return null;
- }
- return data.data;
- }
- return data;
- } catch (error) {
- return value;
- }
- }
- set(
- key: T extends "local" ? LOCAL_STORAGE_KEYS : SESSION_STORAGE_KEYS,
- data: any,
- option?: { expires: string | Date }
- ) {
- let cache: string | Date = "";
- if (option?.expires) {
- try {
- cache = new Date(option.expires);
- } catch (error) {
- console.warn(`set storage ${key} expires error`);
- }
- }
- return this.storage.setItem(key as string, JSON.stringify({ data, cache }));
- }
- remove(key: T extends "local" ? LOCAL_STORAGE_KEYS : SESSION_STORAGE_KEYS) {
- return this.storage.removeItem(key as string);
- }
- clear() {
- return this.storage.clear();
- }
- }
- export const localStorageTool = new StorageTool<"local">("local");
- export const sessionStorageTool = new StorageTool<"session">("session");
|