TTDStorage.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { createStore, get, set } from "idb-keyval";
  2. import type { SavedChats } from "@excalidraw/excalidraw/components/TTDDialog/types";
  3. import { STORAGE_KEYS } from "../app_constants";
  4. /**
  5. * IndexedDB adapter for TTD chat storage.
  6. * Implements TTDPersistenceAdapter interface.
  7. */
  8. export class TTDIndexedDBAdapter {
  9. /** IndexedDB database name */
  10. private static idb_name = STORAGE_KEYS.IDB_TTD_CHATS;
  11. /** Store key for chat data */
  12. private static key = "ttdChats";
  13. private static store = createStore(
  14. `${TTDIndexedDBAdapter.idb_name}-db`,
  15. `${TTDIndexedDBAdapter.idb_name}-store`,
  16. );
  17. /**
  18. * Load saved chats from IndexedDB.
  19. * @returns Promise resolving to saved chats array (empty if none found)
  20. */
  21. static async loadChats(): Promise<SavedChats> {
  22. try {
  23. const data = await get<SavedChats>(
  24. TTDIndexedDBAdapter.key,
  25. TTDIndexedDBAdapter.store,
  26. );
  27. return data || [];
  28. } catch (error) {
  29. console.warn("Failed to load TTD chats from IndexedDB:", error);
  30. return [];
  31. }
  32. }
  33. /**
  34. * Save chats to IndexedDB.
  35. * @param chats - The chats array to persist
  36. */
  37. static async saveChats(chats: SavedChats): Promise<void> {
  38. try {
  39. await set(TTDIndexedDBAdapter.key, chats, TTDIndexedDBAdapter.store);
  40. } catch (error) {
  41. console.warn("Failed to save TTD chats to IndexedDB:", error);
  42. throw error;
  43. }
  44. }
  45. }