54 lines
2.1 KiB
TypeScript
54 lines
2.1 KiB
TypeScript
import { useQuery } from "@tanstack/react-query";
|
|
import { api } from "../lib/api";
|
|
import type { ChatMessage } from "../lib/webrtc";
|
|
|
|
interface ChatHistoryResponse {
|
|
success: boolean;
|
|
messages: ChatMessage[];
|
|
count: number;
|
|
error?: string;
|
|
}
|
|
|
|
export const useChatHistory = (sessionId: string | undefined, enabled = true) => {
|
|
console.log("[useChatHistory] Hook called with:", { sessionId, enabled, willExecute: enabled && !!sessionId });
|
|
|
|
return useQuery({
|
|
queryKey: ["chat-history", sessionId],
|
|
queryFn: async () => {
|
|
console.log("[useChatHistory] Fetching chat history for session:", sessionId);
|
|
|
|
if (!sessionId) {
|
|
console.error("[useChatHistory] Session ID is required but not provided");
|
|
throw new Error("Session ID is required");
|
|
}
|
|
|
|
try {
|
|
console.log("[useChatHistory] Making API request to:", `sessions/${sessionId}/messages`);
|
|
const response = await api
|
|
.get(`sessions/${sessionId}/messages`)
|
|
.json<ChatHistoryResponse>();
|
|
|
|
console.log("[useChatHistory] API response:", response);
|
|
|
|
if (!response.success) {
|
|
console.error("[useChatHistory] API returned error:", response.error);
|
|
throw new Error(response.error || "Failed to load chat history");
|
|
}
|
|
|
|
console.log("[useChatHistory] Successfully loaded", response.messages.length, "messages");
|
|
return response.messages;
|
|
} catch (error) {
|
|
console.error("[useChatHistory] Error fetching chat history:", error);
|
|
throw error;
|
|
}
|
|
},
|
|
enabled: enabled && !!sessionId,
|
|
staleTime: Infinity, // История загружается один раз и больше не обновляется (новые сообщения приходят через WebSocket)
|
|
gcTime: 1000 * 60 * 30, // 30 минут в кэше
|
|
refetchOnWindowFocus: false, // Не перезагружать при фокусе
|
|
refetchOnReconnect: false, // Не перезагружать при реконнекте
|
|
refetchInterval: false, // Не перезагружать автоматически
|
|
});
|
|
};
|
|
|