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

74 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-03-06 03:14:24 +08:00
import { useMutation, useQuery } from '@tanstack/react-query';
2025-02-18 08:30:05 +08:00
import {
getUser,
getUser_server,
updateOrganizationUser,
getMyUserInfo,
getMyUserInfo_server
} from './requests';
2025-03-08 07:02:56 +08:00
import { useMemoizedFn } from '@/hooks';
import { QueryClient, useQueryClient } from '@tanstack/react-query';
2025-02-15 12:02:25 +08:00
import { queryKeys } from '@/api/query_keys';
export const useGetMyUserInfo = () => {
2025-02-19 05:15:01 +08:00
const queryFn = useMemoizedFn(async () => {
return getMyUserInfo();
});
2025-03-06 03:14:24 +08:00
return useQuery({
2025-02-18 13:22:32 +08:00
...queryKeys.userGetUserMyself,
2025-02-15 12:20:22 +08:00
queryFn,
enabled: false //This is a server only query
2025-02-15 12:02:25 +08:00
});
};
2025-02-18 08:30:05 +08:00
export const prefetchGetMyUserInfo = async (
params: Parameters<typeof getMyUserInfo_server>[0],
queryClientProp?: QueryClient
) => {
2025-02-15 12:02:25 +08:00
const queryClient = queryClientProp || new QueryClient();
2025-02-18 08:30:05 +08:00
const initialData = await getMyUserInfo_server(params);
2025-02-15 12:02:25 +08:00
await queryClient.prefetchQuery({
2025-02-18 13:22:32 +08:00
...queryKeys.userGetUserMyself,
2025-02-19 05:15:01 +08:00
queryFn: () => initialData!,
2025-02-18 08:30:05 +08:00
initialData
2025-02-15 12:02:25 +08:00
});
2025-02-18 08:30:05 +08:00
return { queryClient, initialData };
2025-02-15 12:02:25 +08:00
};
export const useGetUser = (params: Parameters<typeof getUser>[0]) => {
2025-02-15 12:20:22 +08:00
const queryFn = useMemoizedFn(() => getUser(params));
2025-03-06 03:14:24 +08:00
return useQuery({
2025-02-18 13:22:32 +08:00
...queryKeys.userGetUser(params.userId),
2025-03-06 03:14:24 +08:00
queryFn
});
};
export const useUpdateUser = () => {
const queryClient = useQueryClient();
const mutationFn = useMemoizedFn(async (params: Parameters<typeof updateOrganizationUser>[0]) => {
2025-02-18 13:22:32 +08:00
const options = queryKeys.userGetUser(params.userId);
2025-02-15 12:20:22 +08:00
queryClient.setQueryData(options.queryKey, (oldData) => {
return {
...oldData!,
...params
};
});
const res = await updateOrganizationUser(params);
return res;
});
2025-03-06 03:14:24 +08:00
return useMutation({
mutationFn: mutationFn
});
};
export const prefetchGetUser = async (userId: string, queryClientProp?: QueryClient) => {
const queryClient = queryClientProp || new QueryClient();
await queryClient.prefetchQuery({
2025-02-18 13:22:32 +08:00
...queryKeys.userGetUser(userId),
queryFn: () => getUser_server({ userId })
});
return queryClient;
};