SurfSense/surfsense_web/atoms/chats/chat-querie.atoms.ts

55 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-11-12 13:27:15 +02:00
import { atom } from "jotai";
import { atomWithQuery } from "jotai-tanstack-query";
import type { ChatDetails } from "@/app/dashboard/[search_space_id]/chats/chats-client";
import type { PodcastItem } from "@/app/dashboard/[search_space_id]/podcasts/podcasts-client";
2025-11-15 02:07:20 +02:00
import { activeSearchSpaceIdAtom } from "@/atoms/seach-spaces/seach-space-queries.atom";
2025-11-15 03:28:33 +02:00
import { chatApiService } from "@/lib/apis/chats-api.service";
2025-11-12 16:22:30 +02:00
import { getPodcastByChatId } from "@/lib/apis/podcasts.api";
2025-11-12 13:27:15 +02:00
import { cacheKeys } from "@/lib/query-client/cache-keys";
type ActiveChatState = {
2025-11-14 00:42:19 +02:00
chatId: string | null;
chatDetails: ChatDetails | null;
podcast: PodcastItem | null;
2025-11-12 13:27:15 +02:00
};
export const activeChatIdAtom = atom<string | null>(null);
export const activeChatAtom = atomWithQuery<ActiveChatState>((get) => {
2025-11-14 00:42:19 +02:00
const activeChatId = get(activeChatIdAtom);
const authToken = localStorage.getItem("surfsense_bearer_token");
return {
queryKey: cacheKeys.activeSearchSpace.activeChat(activeChatId ?? ""),
enabled: !!activeChatId && !!authToken,
queryFn: async () => {
if (!authToken) {
throw new Error("No authentication token found");
}
if (!activeChatId) {
throw new Error("No active chat id found");
}
const [podcast, chatDetails] = await Promise.all([
getPodcastByChatId(activeChatId, authToken),
2025-11-15 03:28:33 +02:00
chatApiService.getChatDetails({ id: Number(activeChatId) }),
2025-11-14 00:42:19 +02:00
]);
return { chatId: activeChatId, chatDetails, podcast };
},
};
2025-11-12 13:27:15 +02:00
});
2025-11-12 16:22:30 +02:00
export const activeSearchSpaceChatsAtom = atomWithQuery((get) => {
2025-11-14 00:42:19 +02:00
const searchSpaceId = get(activeSearchSpaceIdAtom);
const authToken = localStorage.getItem("surfsense_bearer_token");
return {
queryKey: cacheKeys.activeSearchSpace.chats(searchSpaceId ?? ""),
enabled: !!searchSpaceId && !!authToken,
queryFn: async () => {
2025-11-15 03:28:33 +02:00
return chatApiService.getChatsBySearchSpace({ search_space_id: Number(searchSpaceId) });
2025-11-14 00:42:19 +02:00
},
};
2025-11-12 16:22:30 +02:00
});