import { ApiRequestError, normalizeApiError } from '~/utils/errors' type ApiMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE' interface RequestOptions { method?: ApiMethod body?: unknown query?: Record contentType?: string } const PUBLIC_PREFIXES = ['/setup', '/login', '/register', '/join'] export function useApi() { const router = useRouter() const route = useRoute() const csrf = useCookie('together_csrf', { sameSite: 'lax' }) function mayRedirect() { return !PUBLIC_PREFIXES.some((prefix) => route.path === prefix || route.path.startsWith(`${prefix}/`)) } async function request(path: string, options: RequestOptions = {}): Promise { const method = options.method ?? 'GET' const headers: Record = { Accept: 'application/json' } if (options.contentType) headers['Content-Type'] = options.contentType if (method !== 'GET' && csrf.value) headers['X-CSRF-Token'] = csrf.value try { return await $fetch(path, { baseURL: '/api', method, body: options.body as Record | undefined, query: options.query, headers, credentials: 'include', retry: 0, }) } catch (error) { const failure = normalizeApiError(error) if (failure.status === 401 && mayRedirect()) { void router.replace('/login') } throw failure } } return { get: (path: string, query?: RequestOptions['query']) => request(path, { query }), post: (path: string, body?: unknown) => request(path, { method: 'POST', body }), upload: (path: string, body: Blob) => request(path, { method: 'POST', body, contentType: body.type || 'application/octet-stream', }), patch: (path: string, body?: unknown) => request(path, { method: 'PATCH', body }), del: (path: string) => request(path, { method: 'DELETE' }), ApiRequestError, } }