aboutsummaryrefslogtreecommitdiffstats
path: root/apps/browser-extension/src/utils/storagePersister.ts
blob: 186faa4d1a25b35e81c11b07fe6e2a474a1df9bf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import {
  PersistedClient,
  Persister,
} from "@tanstack/react-query-persist-client";

export const TANSTACK_QUERY_CACHE_KEY = "tanstack-query-cache-key";

// Declare chrome namespace for TypeScript
declare const chrome: {
  storage: {
    local: {
      set: (items: Record<string, string>) => Promise<void>;
      get: (keys: string | string[]) => Promise<Record<string, string>>;
      remove: (keys: string | string[]) => Promise<void>;
    };
  };
};

/**
 * Creates an AsyncStorage-like interface for Chrome's extension storage.
 *
 * @param storage The Chrome storage area to use (e.g., `chrome.storage.local`).
 * @returns An object that mimics the AsyncStorage interface.
 */
export const createChromeStorage = (
  storage: typeof chrome.storage.local = globalThis.chrome?.storage?.local,
): Persister => {
  // Check if we are in a Chrome extension environment
  if (typeof chrome === "undefined" || !chrome.storage) {
    // Return a noop persister for non-extension environments
    return {
      persistClient: async () => {
        return;
      },
      restoreClient: async () => undefined,
      removeClient: async () => {
        return;
      },
    };
  }

  return {
    persistClient: async (client: PersistedClient) => {
      await storage.set({ [TANSTACK_QUERY_CACHE_KEY]: JSON.stringify(client) });
    },
    restoreClient: async () => {
      const result = await storage.get(TANSTACK_QUERY_CACHE_KEY);
      return result[TANSTACK_QUERY_CACHE_KEY]
        ? JSON.parse(result[TANSTACK_QUERY_CACHE_KEY])
        : undefined;
    },
    removeClient: async () => {
      await storage.remove(TANSTACK_QUERY_CACHE_KEY);
    },
  };
};