import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api } from './client' import type { components } from './schema' export type User = components['schemas']['User'] const USERS = ['users'] /** Every account, oldest first. Admins only. */ export function useUsers() { return useQuery({ queryKey: USERS, queryFn: () => api.get<{ users: User[] }>('/users'), select: (data) => data.users, }) } export function useCreateUser() { const client = useQueryClient() return useMutation({ mutationFn: (body: { email: string; password: string; is_admin: boolean }) => api.post('/users', body), onSuccess: () => client.invalidateQueries({ queryKey: USERS }), }) } /** Gives or takes away the admin role. The last admin cannot lose it (`last_admin`). */ export function useSetAdmin() { const client = useQueryClient() return useMutation({ mutationFn: ({ id, is_admin }: { id: number; is_admin: boolean }) => api.patch(`/users/${id}`, { is_admin }), onSuccess: () => client.invalidateQueries({ queryKey: USERS }), }) } /** * Sets a new password and ends every session of that account. Nothing about the account changes, so the list * is not read again. The password is in the mutation's variables until `reset()` is called: callers do that. */ export function useResetPassword() { return useMutation({ mutationFn: ({ id, password }: { id: number; password: string }) => api.put(`/users/${id}/password`, { password }), }) } export function useDeleteUser() { const client = useQueryClient() return useMutation({ mutationFn: (id: number) => api.del(`/users/${id}`), onSuccess: () => client.invalidateQueries({ queryKey: USERS }), }) }