import { useMutation, useQuery, useQueryClient, type QueryKey } from '@tanstack/react-query' import type { Doc, DocKind, DocValue, SingletonKey, SingletonValue } from '../../shared/schemas.ts' import { useChannel } from './channel.tsx' import { toast } from './toast.ts' export class ApiError extends Error { status: number issues?: { path: (string | number)[]; message: string }[] /** The full JSON error body, for endpoint-specific flags like `reconnect`. */ body: Record | null constructor(status: number, message: string, issues?: ApiError['issues'], body: Record | null = null) { super(message) this.status = status this.issues = issues this.body = body } } async function request(method: string, path: string, body?: unknown): Promise { const res = await fetch(`/api${path}`, { method, credentials: 'same-origin', headers: body !== undefined ? { 'content-type': 'application/json' } : undefined, body: body !== undefined ? JSON.stringify(body) : undefined, }) const text = await res.text() const data = text ? JSON.parse(text) : null if (!res.ok) throw new ApiError(res.status, data?.error ?? `Request failed (${res.status})`, data?.issues, data) return data as T } export const api = { get: (path: string) => request('GET', path), post: (path: string, body?: unknown) => request('POST', path, body ?? {}), put: (path: string, body: unknown) => request('PUT', path, body), patch: (path: string, body: unknown) => request('PATCH', path, body), del: (path: string) => request('DELETE', path), } export const cpath = (cid: string, rest = '') => `/c/${encodeURIComponent(cid)}${rest}` /** Friendly text for a failed request, including the first field issue. */ export function errorMessage(err: unknown): string { if (err instanceof ApiError) { const issue = err.issues?.[0] return issue ? `${issue.path.join(' → ') || 'Value'}: ${issue.message}` : err.message } return err instanceof Error ? err.message : 'Something went wrong.' } // --- typed hooks ------------------------------------------------------------------ export function useApi(key: QueryKey, path: string | null, opts: { refetchInterval?: number } = {}) { return useQuery({ queryKey: key, queryFn: () => api.get(path!), enabled: path !== null, ...opts }) } export function useDocs(kind: K) { const { cid } = useChannel() return useQuery({ queryKey: ['docs', cid, kind], queryFn: () => api.get[]>(cpath(cid, `/docs/${kind}`)) }) } export function useSaveDoc(kind: K) { const { cid } = useChannel() const qc = useQueryClient() return useMutation({ mutationFn: ({ id, data }: { id?: string; data: Partial> | Record }) => id ? api.put>(cpath(cid, `/docs/${kind}/${id}`), data) : api.post>(cpath(cid, `/docs/${kind}`), data), onSuccess: () => qc.invalidateQueries({ queryKey: ['docs', cid, kind] }), }) } export function useDeleteDoc(kind: DocKind) { const { cid } = useChannel() const qc = useQueryClient() return useMutation({ mutationFn: (id: string) => api.del(cpath(cid, `/docs/${kind}/${id}`)), onSuccess: () => qc.invalidateQueries({ queryKey: ['docs', cid, kind] }), onError: (err) => toast.error(errorMessage(err)), }) } /** Toggle a doc's `enabled` flag in place with an optimistic update. */ export function useToggleDoc(kind: K) { const { cid } = useChannel() const qc = useQueryClient() return useMutation({ mutationFn: (doc: Doc) => api.put(cpath(cid, `/docs/${kind}/${doc.id}`), { ...doc.data, enabled: !(doc.data as { enabled: boolean }).enabled }), onMutate: async (doc) => { const key = ['docs', cid, kind] await qc.cancelQueries({ queryKey: key }) const prev = qc.getQueryData[]>(key) qc.setQueryData[]>(key, (old) => old?.map((d) => (d.id === doc.id ? { ...d, data: { ...d.data, enabled: !(d.data as { enabled: boolean }).enabled } } : d))) return { prev } }, onError: (err, _doc, ctx) => { qc.setQueryData(['docs', cid, kind], ctx?.prev) toast.error(errorMessage(err)) }, onSettled: () => qc.invalidateQueries({ queryKey: ['docs', cid, kind] }), }) } export function useSingleton(key: K) { const { cid } = useChannel() return useQuery({ queryKey: ['settings', cid, key], queryFn: () => api.get>(cpath(cid, `/settings/${key}`)) }) } export function useSaveSingleton(key: K) { const { cid } = useChannel() const qc = useQueryClient() return useMutation({ mutationFn: (value: SingletonValue) => api.put>(cpath(cid, `/settings/${key}`), value), onSuccess: (data) => { qc.setQueryData(['settings', cid, key], data) }, }) }