54 lines
1.6 KiB
TypeScript
54 lines
1.6 KiB
TypeScript
import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
|
|
import { getCurrentUserRepos, projectRepos, projectRepoCreate } from "@/client/api";
|
|
import type { UserRepoInfo, ProjectRepositoryItem, ProjectRepoCreateParams } from "@/client/model";
|
|
|
|
const QUERY_KEY = "repos";
|
|
const PROJECT_REPOS_QUERY_KEY = "projectRepos";
|
|
|
|
export function useProjectReposQuery(projectName: string | undefined) {
|
|
return useQuery({
|
|
queryKey: [PROJECT_REPOS_QUERY_KEY, projectName],
|
|
queryFn: async (): Promise<ProjectRepositoryItem[]> => {
|
|
if (!projectName) return [];
|
|
const res = await projectRepos(projectName);
|
|
return res.data?.data?.items ?? [];
|
|
},
|
|
enabled: !!projectName,
|
|
staleTime: 5 * 60 * 1000,
|
|
});
|
|
}
|
|
|
|
export function useReposQuery() {
|
|
return useQuery({
|
|
queryKey: [QUERY_KEY],
|
|
queryFn: async (): Promise<UserRepoInfo[]> => {
|
|
const res = await getCurrentUserRepos();
|
|
return res.data?.data?.repos ?? [];
|
|
},
|
|
staleTime: 5 * 60 * 1000,
|
|
});
|
|
}
|
|
|
|
export function useInvalidateRepos() {
|
|
const queryClient = useQueryClient();
|
|
return () => {
|
|
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
|
|
queryClient.invalidateQueries({ queryKey: [PROJECT_REPOS_QUERY_KEY] });
|
|
};
|
|
}
|
|
|
|
export function useCreateRepoMutation(projectName: string | undefined) {
|
|
const invalidate = useInvalidateRepos();
|
|
|
|
return useMutation({
|
|
mutationFn: async (params: ProjectRepoCreateParams) => {
|
|
if (!projectName) throw new Error("No project selected");
|
|
const res = await projectRepoCreate(projectName, params);
|
|
return res.data?.data;
|
|
},
|
|
onSuccess: () => {
|
|
invalidate();
|
|
},
|
|
});
|
|
}
|