feat(web): hooks for listing, creating, changing and deleting users

Listing, creating, giving or taking the admin role, resetting a password and deleting, each refreshing the list when the list changes.
This commit is contained in:
tgiachi 2026-11-12 14:55:26 +01:00
commit b190835185
2 changed files with 126 additions and 0 deletions

View file

@ -0,0 +1,75 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { expect, test } from 'vitest'
import { mockFetch } from '@/test/mockFetch'
import { useCreateUser, useDeleteUser, useResetPassword, useSetAdmin, useUsers } from './users'
function setup() {
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
return { client, wrapper }
}
const user = (id: number, is_admin = false) => ({ id, email: `u${id}@example.org`, is_admin })
const none = () => new Response(null, { status: 204 })
const json = (body: object, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
test('the users are listed, oldest first as the server sends them', async () => {
mockFetch({ 'GET /api/v1/users': () => ({ users: [user(1, true), user(2)] }) })
const { result } = renderHook(() => useUsers(), { wrapper: setup().wrapper })
await waitFor(() => expect(result.current.data).toHaveLength(2))
expect(result.current.data?.[0].email).toBe('u1@example.org')
})
test('creating sends the email, the password and the role, and the list is read again', async () => {
let users = [user(1, true)]
const { calls } = mockFetch({
'GET /api/v1/users': () => ({ users }),
'POST /api/v1/users': ({ init }) => {
const body = JSON.parse(String(init.body))
users = [...users, user(2, body.is_admin)]
return json(users[1], 201)
},
})
const { wrapper } = setup()
const { result } = renderHook(() => ({ list: useUsers(), create: useCreateUser() }), { wrapper })
await waitFor(() => expect(result.current.list.data).toHaveLength(1))
await act(() => result.current.create.mutateAsync({ email: 'new@example.org', password: 'correct horse', is_admin: true }))
await waitFor(() => expect(result.current.list.data).toHaveLength(2))
expect(JSON.parse(String(calls.find((c) => c.key === 'POST /api/v1/users')?.init.body))).toEqual({
email: 'new@example.org',
password: 'correct horse',
is_admin: true,
})
})
test('giving or taking the admin role is a PATCH with the role only', async () => {
const { calls } = mockFetch({ 'PATCH /api/v1/users/2': () => user(2, true), 'GET /api/v1/users': () => ({ users: [] }) })
const { result } = renderHook(() => useSetAdmin(), { wrapper: setup().wrapper })
await act(() => result.current.mutateAsync({ id: 2, is_admin: true }))
await act(() => result.current.mutateAsync({ id: 2, is_admin: false }))
const bodies = calls.filter((c) => c.key === 'PATCH /api/v1/users/2').map((c) => JSON.parse(String(c.init.body)))
expect(bodies).toEqual([{ is_admin: true }, { is_admin: false }])
})
test('resetting a password is a PUT with the new password, and the list is not read again', async () => {
const { calls } = mockFetch({ 'PUT /api/v1/users/2/password': none, 'GET /api/v1/users': () => ({ users: [] }) })
const { wrapper } = setup()
const { result } = renderHook(() => ({ list: useUsers(), reset: useResetPassword() }), { wrapper })
await waitFor(() => expect(result.current.list.isSuccess).toBe(true))
await act(() => result.current.reset.mutateAsync({ id: 2, password: 'a brand new one' }))
await new Promise((r) => setTimeout(r, 30))
expect(JSON.parse(String(calls.find((c) => c.key === 'PUT /api/v1/users/2/password')?.init.body))).toEqual({ password: 'a brand new one' })
expect(calls.filter((c) => c.key === 'GET /api/v1/users')).toHaveLength(1)
})
test('deleting removes that account and the list is read again', async () => {
const { calls } = mockFetch({ 'DELETE /api/v1/users/2': none, 'GET /api/v1/users': () => ({ users: [user(1, true)] }) })
const { wrapper } = setup()
const { result } = renderHook(() => ({ list: useUsers(), del: useDeleteUser() }), { wrapper })
await waitFor(() => expect(result.current.list.isSuccess).toBe(true))
await act(() => result.current.del.mutateAsync(2))
await waitFor(() => expect(calls.filter((c) => c.key === 'GET /api/v1/users')).toHaveLength(2))
expect(calls.map((c) => c.key)).toContain('DELETE /api/v1/users/2')
})

51
web/src/api/users.ts Normal file
View file

@ -0,0 +1,51 @@
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<User>('/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<User>(`/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 }),
})
}