videos.ts79 lines, 2.0 KB
| 1 | import { JobStatus, Video } from "@/lib/api/types"; |
| 2 | import { |
| 3 | getAllJobs, |
| 4 | getJobStatus, |
| 5 | getUserVideos, |
| 6 | getVideoById, |
| 7 | cancelJob, |
| 8 | } from "@/lib/api/videos"; |
| 9 | import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query"; |
| 10 | import { ApiError } from "@/lib/api/types"; |
| 11 | import { toast } from "sonner"; |
| 12 | |
| 13 | export function useAllJobs() { |
| 14 | return useQuery({ |
| 15 | queryKey: ["jobs"], |
| 16 | queryFn: getAllJobs, |
| 17 | //poll every 5 seconds |
| 18 | refetchInterval: 5000, |
| 19 | }); |
| 20 | } |
| 21 | |
| 22 | export function useJobStatus(jobId: string) { |
| 23 | return useQuery({ |
| 24 | queryKey: ["job-status", jobId], |
| 25 | queryFn: () => getJobStatus(jobId), |
| 26 | refetchInterval: (query) => { |
| 27 | const data = query.state.data as JobStatus | undefined; |
| 28 | if (data?.state === "waiting" || data?.state === "active") { |
| 29 | return 3000; |
| 30 | } |
| 31 | return false; |
| 32 | }, |
| 33 | staleTime: 0, |
| 34 | refetchOnWindowFocus: true, |
| 35 | }); |
| 36 | } |
| 37 | |
| 38 | export function useUserVideos() { |
| 39 | return useQuery<Video[]>({ |
| 40 | queryKey: ["videos"], |
| 41 | queryFn: getUserVideos, |
| 42 | }); |
| 43 | } |
| 44 | |
| 45 | export function useVideoById(videoId: string) { |
| 46 | return useQuery<Video>({ |
| 47 | queryKey: ["video", videoId], |
| 48 | queryFn: () => getVideoById(videoId), |
| 49 | enabled: !!videoId, |
| 50 | }); |
| 51 | } |
| 52 | |
| 53 | export function useVideo(videoId: string) { |
| 54 | return useQuery<Video>({ |
| 55 | queryKey: ["video", videoId], |
| 56 | queryFn: () => getVideoById(videoId), |
| 57 | enabled: !!videoId, |
| 58 | }); |
| 59 | } |
| 60 | |
| 61 | // *** NEW HOOK: useCancelJob *** |
| 62 | export function useCancelJob() { |
| 63 | const queryClient = useQueryClient(); |
| 64 | |
| 65 | return useMutation({ |
| 66 | mutationFn: (jobId: string) => cancelJob(jobId), |
| 67 | onSuccess: (data, jobId) => { |
| 68 | // Invalidate queries that depend on the job list or specific job status |
| 69 | queryClient.invalidateQueries({ queryKey: ["jobs"] }); |
| 70 | // Optionally invalidate specific job status query if you have one |
| 71 | // queryClient.invalidateQueries({ queryKey: ['job', jobId] }); |
| 72 | toast.success(data.message || "Job cancelled."); |
| 73 | }, |
| 74 | onError: (error: ApiError) => { |
| 75 | toast.error(error.message || "Could not cancel the job."); |
| 76 | }, |
| 77 | }); |
| 78 | } |
| 79 | // *** END NEW HOOK *** |