81 lines
2.6 KiB
TypeScript
81 lines
2.6 KiB
TypeScript
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import {
|
|
getChatList,
|
|
createChat,
|
|
markChatAsRead,
|
|
getChatDetail,
|
|
} from "../service/Service";
|
|
import { CreateChatRequest } from "../types/ProfileTypes";
|
|
|
|
// Get chat list
|
|
export const useChatList = (options?: { enabled?: boolean }) => {
|
|
return useQuery({
|
|
queryKey: ["chat", "list"],
|
|
queryFn: getChatList,
|
|
staleTime: 1000 * 60 * 5, // 5 minutes
|
|
enabled: options?.enabled ?? true,
|
|
});
|
|
};
|
|
|
|
// Create new chat
|
|
export const useCreateChat = () => {
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: (chatData: CreateChatRequest) => createChat(chatData),
|
|
onSuccess: () => {
|
|
// Invalidate chat list to refetch
|
|
queryClient.invalidateQueries({ queryKey: ["chat", "list"] });
|
|
},
|
|
});
|
|
};
|
|
|
|
// Mark chat as read
|
|
export const useMarkChatAsRead = () => {
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: (chatId: string) => {
|
|
console.log("📤 ارسال درخواست markAsRead برای:", chatId);
|
|
return markChatAsRead(chatId);
|
|
},
|
|
retry: (failureCount, error: unknown) => {
|
|
// اگر ۴۰۴ است، retry نکن
|
|
const axiosError = error as { response?: { status?: number } };
|
|
if (axiosError?.response?.status === 404) {
|
|
console.log("ℹ️ چت یافت نشد یا قبلاً mark شده - retry نمیکنیم");
|
|
return false;
|
|
}
|
|
// برای سایر خطاها، حداکثر ۱ بار retry کن
|
|
return failureCount < 1;
|
|
},
|
|
retryDelay: 1000,
|
|
onSuccess: (_, chatId) => {
|
|
console.log(
|
|
"✅ پیامها با موفقیت به عنوان خوانده شده علامتگذاری شدند:",
|
|
chatId
|
|
);
|
|
// Update chat list to reflect read status
|
|
queryClient.invalidateQueries({ queryKey: ["chat", "list"] });
|
|
// Update messages to mark as read
|
|
queryClient.invalidateQueries({ queryKey: ["chat", "messages", chatId] });
|
|
},
|
|
onError: (error: unknown, chatId) => {
|
|
console.error("❌ خطا در markAsRead:", chatId, error);
|
|
// اگر ۴۰۴ دریافت کردیم، شاید چت وجود ندارد یا قبلاً mark شده
|
|
const axiosError = error as { response?: { status?: number } };
|
|
if (axiosError?.response?.status === 404) {
|
|
console.log("ℹ️ چت یافت نشد یا قبلاً mark شده:", chatId);
|
|
}
|
|
},
|
|
});
|
|
};
|
|
|
|
export const useChatDetail = (chatId?: string) => {
|
|
return useQuery({
|
|
queryKey: ["chat", "detail", chatId],
|
|
queryFn: () => getChatDetail(chatId!),
|
|
enabled: !!chatId,
|
|
});
|
|
};
|