import type { FetchError } from 'ofetch' import type { ApiResponse } from '~/types/api-response' /** * Thin wrapper around $fetch for the Yale Access API. * Always resolves to an ApiResponse (never throws), and sends the user * back to the login page when the server session has expired. */ export function useApi() { const config = useRuntimeConfig() const authenticated = useCookie('authenticated') async function request(path: string, method: 'GET' | 'POST' | 'DELETE' = 'GET', body?: unknown): Promise> { try { return await $fetch>(path, { baseURL: config.public.apiBaseUrl, method, credentials: 'include', // The API takes bare JSON strings for some bodies, so always JSON-encode ...(body !== undefined && { body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }) }) } catch (e) { const err = e as FetchError> // The cookie auth middleware answers an expired session with an empty 401 if (err.status === 401 && !err.data?.error) { authenticated.value = false await navigateTo('/login') return { success: false, error: 'Your session has expired. Please log in again.' } } return err.data?.error ? { success: false, error: err.data.error } : { success: false, error: 'Unable to reach the server.' } } } return { get: (path: string) => request(path), post: (path: string, body?: unknown) => request(path, 'POST', body), delete: (path: string) => request(path, 'DELETE') } }