Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import { 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<Pick<Item, "name" | "description" | "tags" | "category">>; }, ) => 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<typeof useQueryClient>, categoryId: CategoryId,) { return Promise.all( matchupAffectedKeys(categoryId).map((queryKey) => queryClient.invalidateQueries({ queryKey }) ), );}