import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { createItem, deleteItem, leaderboard, listItems, resetCategoryRatings, updateItem, } from "@/db/repositories/items.ts"; import { matchupAffectedKeys, queryKeys } from "@/queries/keys.ts"; import type { CategoryId, Item, ItemId, NewItem } from "@/domain/types.ts"; export function useItems(categoryId: CategoryId) { return useQuery({ queryKey: queryKeys.items(categoryId), queryFn: () => listItems(categoryId), }); } export function useLeaderboard(categoryId: CategoryId) { return useQuery({ queryKey: queryKeys.leaderboard(categoryId), queryFn: () => leaderboard(categoryId), }); } export function useCreateItem(categoryId: CategoryId) { const queryClient = useQueryClient(); return useMutation({ mutationFn: (input: NewItem) => createItem(input), onSuccess: () => invalidateCategory(queryClient, categoryId), }); } export function useUpdateItem(categoryId: CategoryId) { const queryClient = useQueryClient(); return useMutation({ mutationFn: ( { id, patch }: { id: ItemId; patch: Partial>; }, ) => updateItem(id, patch), onSuccess: () => invalidateCategory(queryClient, categoryId), }); } export function useDeleteItem(categoryId: CategoryId) { const queryClient = useQueryClient(); return useMutation({ mutationFn: (id: ItemId) => deleteItem(id), onSuccess: () => invalidateCategory(queryClient, categoryId), }); } export function useResetRatings(categoryId: CategoryId) { const queryClient = useQueryClient(); return useMutation({ mutationFn: () => resetCategoryRatings(categoryId), onSuccess: () => invalidateCategory(queryClient, categoryId), }); } function invalidateCategory( queryClient: ReturnType, categoryId: CategoryId, ) { return Promise.all( matchupAffectedKeys(categoryId).map((queryKey) => queryClient.invalidateQueries({ queryKey }) ), ); }