buster/web/src/api/buster_rest/chats/queryRequests.ts

77 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-02-08 10:57:42 +08:00
import { useMemoizedFn } from 'ahooks';
2025-03-06 03:14:24 +08:00
import { QueryClient, useQuery } from '@tanstack/react-query';
import { getListChats, getListChats_server, getChat, getChat_server } from './requests';
2025-02-18 11:50:21 +08:00
import type { BusterChatListItem } from '@/api/asset_interfaces';
import { queryKeys } from '@/api/query_keys';
2025-02-22 03:07:30 +08:00
import { updateChatToIChat } from '@/lib/chat';
2025-03-06 03:14:24 +08:00
import type { IBusterChat } from '@/context/Chats';
import { RustApiError } from '@/api/buster_rest/errors';
2025-02-08 10:57:42 +08:00
export const useGetListChats = (params?: Parameters<typeof getListChats>[0]) => {
2025-02-18 11:50:21 +08:00
const queryFn = useMemoizedFn((): Promise<BusterChatListItem[]> => {
return getListChats(params);
2025-02-08 10:57:42 +08:00
});
2025-03-06 03:14:24 +08:00
const res = useQuery({
2025-02-18 11:50:21 +08:00
...queryKeys.chatsGetList(params),
2025-02-08 10:57:42 +08:00
queryFn
});
return {
...res,
data: res.data || []
};
};
export const prefetchGetListChats = async (
params?: Parameters<typeof getListChats>[0],
2025-02-08 10:57:42 +08:00
queryClientProp?: QueryClient
) => {
const queryClient = queryClientProp || new QueryClient();
await queryClient.prefetchQuery({
2025-02-18 11:50:21 +08:00
...queryKeys.chatsGetList(params),
queryFn: () => getListChats_server(params)
});
return queryClient;
};
export const useGetChat = (params: Parameters<typeof getChat>[0]) => {
2025-02-18 11:50:21 +08:00
const queryFn = useMemoizedFn(async () => {
2025-03-06 01:13:24 +08:00
return await getChat(params).then((chat) => {
return updateChatToIChat(chat, true).iChat;
});
});
2025-03-06 03:14:24 +08:00
useQuery({
2025-02-18 11:50:21 +08:00
...queryKeys.chatsGetChat(params.id),
queryFn,
2025-03-06 01:13:24 +08:00
enabled: !!params.id
});
2025-03-06 03:14:24 +08:00
return useQuery<IBusterChat, RustApiError>({
...queryKeys.chatsGetChat(params.id),
queryKey: queryKeys.chatsGetChat(params.id).queryKey,
enabled: !!params.id
});
};
export const prefetchGetChat = async (
params: Parameters<typeof getChat>[0],
queryClientProp?: QueryClient
) => {
const queryClient = queryClientProp || new QueryClient();
await queryClient.prefetchQuery({
2025-02-18 11:50:21 +08:00
...queryKeys.chatsGetChat(params.id),
queryFn: async () => {
2025-03-06 01:13:24 +08:00
return await getChat_server(params).then((chat) => {
return updateChatToIChat(chat, true).iChat;
});
2025-02-18 11:50:21 +08:00
}
2025-02-08 10:57:42 +08:00
});
return queryClient;
};