One set of hooks for the three jobs: read the status (again and again while it runs, by itself stopping), start (optionally reading everything again) and stop.
42 lines
1.9 KiB
TypeScript
42 lines
1.9 KiB
TypeScript
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
import { api } from './client'
|
|
import type { components } from './schema'
|
|
|
|
export type CoversJobStatus = components['schemas']['CoversJobStatus']
|
|
export type ArtistJobStatus = components['schemas']['ArtistJobStatus']
|
|
|
|
/** The bulk jobs that go through the whole library, each at its own address under `/library`. */
|
|
export type JobKind = 'covers' | 'artist-images' | 'descriptions'
|
|
export type JobStatus<K extends JobKind> = K extends 'covers' ? CoversJobStatus : ArtistJobStatus
|
|
|
|
const statusKey = (kind: JobKind) => ['library', kind]
|
|
|
|
/** Whether the job runs, how far it is, and how the last one ended. While it runs it is read again every `intervalMs`. */
|
|
export function useJobStatus<K extends JobKind>(kind: K, { intervalMs = 2000 }: { intervalMs?: number } = {}) {
|
|
return useQuery({
|
|
queryKey: statusKey(kind),
|
|
queryFn: () => api.get<JobStatus<K>>(`/library/${kind}`),
|
|
refetchInterval: (query) => (query.state.data?.running ? intervalMs : false),
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Starts the job in the background. `refresh` goes through every item again, also those with a good answer.
|
|
* Whatever the answer (also "already running"), the status is read at once so the page follows the job.
|
|
*/
|
|
export function useStartJob(kind: JobKind) {
|
|
const client = useQueryClient()
|
|
return useMutation({
|
|
mutationFn: ({ refresh }: { refresh: boolean }) => api.post<{ status: 'started' }>(refresh ? `/library/${kind}?refresh=true` : `/library/${kind}`),
|
|
onSettled: () => client.invalidateQueries({ queryKey: statusKey(kind) }),
|
|
})
|
|
}
|
|
|
|
/** Asks the job to end after the item it is on. What it already did stays. */
|
|
export function useStopJob(kind: JobKind) {
|
|
const client = useQueryClient()
|
|
return useMutation({
|
|
mutationFn: () => api.del(`/library/${kind}`),
|
|
onSettled: () => client.invalidateQueries({ queryKey: statusKey(kind) }),
|
|
})
|
|
}
|