Something went wrong. Try again.
fossabot clone for streamplace superbot.mmatt.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import { 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<string, unknown> | null constructor(status: number, message: string, issues?: ApiError['issues'], body: Record<string, unknown> | null = null) { super(message) this.status = status this.issues = issues this.body = body }}
async function request<T>(method: string, path: string, body?: unknown): Promise<T> { 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: <T>(path: string) => request<T>('GET', path), post: <T>(path: string, body?: unknown) => request<T>('POST', path, body ?? {}), put: <T>(path: string, body: unknown) => request<T>('PUT', path, body), patch: <T>(path: string, body: unknown) => request<T>('PATCH', path, body), del: <T>(path: string) => request<T>('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<T>(key: QueryKey, path: string | null, opts: { refetchInterval?: number } = {}) { return useQuery({ queryKey: key, queryFn: () => api.get<T>(path!), enabled: path !== null, ...opts })}
export function useDocs<K extends DocKind>(kind: K) { const { cid } = useChannel() return useQuery({ queryKey: ['docs', cid, kind], queryFn: () => api.get<Doc<K>[]>(cpath(cid, `/docs/${kind}`)) })}
export function useSaveDoc<K extends DocKind>(kind: K) { const { cid } = useChannel() const qc = useQueryClient() return useMutation({ mutationFn: ({ id, data }: { id?: string; data: Partial<DocValue<K>> | Record<string, unknown> }) => id ? api.put<Doc<K>>(cpath(cid, `/docs/${kind}/${id}`), data) : api.post<Doc<K>>(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<K extends DocKind>(kind: K) { const { cid } = useChannel() const qc = useQueryClient() return useMutation({ mutationFn: (doc: Doc<K>) => 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<Doc<K>[]>(key) qc.setQueryData<Doc<K>[]>(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<K extends SingletonKey>(key: K) { const { cid } = useChannel() return useQuery({ queryKey: ['settings', cid, key], queryFn: () => api.get<SingletonValue<K>>(cpath(cid, `/settings/${key}`)) })}
export function useSaveSingleton<K extends SingletonKey>(key: K) { const { cid } = useChannel() const qc = useQueryClient() return useMutation({ mutationFn: (value: SingletonValue<K>) => api.put<SingletonValue<K>>(cpath(cid, `/settings/${key}`), value), onSuccess: (data) => { qc.setQueryData(['settings', cid, key], data) }, })}