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

49 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-11-12 13:27:15 +02:00
import { atomWithQuery } from "jotai-tanstack-query";
import { activeSearchSpaceIdAtom } from "@/atoms/search-spaces/search-space-query.atoms";
2025-11-18 11:35:06 +02:00
import { chatsApiService } from "@/lib/apis/chats-api.service";
import { podcastsApiService } from "@/lib/apis/podcasts-api.service";
import { getBearerToken } from "@/lib/auth-utils";
2025-11-12 13:27:15 +02:00
import { cacheKeys } from "@/lib/query-client/cache-keys";
2025-11-18 22:12:47 +02:00
import { activeChatIdAtom, globalChatsQueryParamsAtom } from "./ui.atoms";
2025-11-12 13:27:15 +02:00
2025-11-18 18:35:48 +02:00
export const activeChatAtom = atomWithQuery((get) => {
2025-11-14 00:42:19 +02:00
const activeChatId = get(activeChatIdAtom);
const authToken = getBearerToken();
2025-11-14 00:42:19 +02:00
return {
2025-11-18 22:12:47 +02:00
queryKey: cacheKeys.chats.activeChat(activeChatId ?? ""),
2025-11-14 00:42:19 +02:00
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([
2025-11-18 11:35:06 +02:00
podcastsApiService.getPodcastByChatId({ chat_id: Number(activeChatId) }),
chatsApiService.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
2025-11-18 22:12:47 +02:00
export const chatsAtom = atomWithQuery((get) => {
2025-11-14 00:42:19 +02:00
const searchSpaceId = get(activeSearchSpaceIdAtom);
const authToken = getBearerToken();
2025-11-18 22:12:47 +02:00
const queryParams = get(globalChatsQueryParamsAtom);
2025-11-14 00:42:19 +02:00
return {
2025-11-18 22:12:47 +02:00
queryKey: cacheKeys.chats.globalQueryParams(queryParams),
2025-11-14 00:42:19 +02:00
enabled: !!searchSpaceId && !!authToken,
queryFn: async () => {
2025-11-18 22:12:47 +02:00
return chatsApiService.getChats({
queryParams: queryParams,
});
2025-11-14 00:42:19 +02:00
},
};
2025-11-12 16:22:30 +02:00
});