Files
LiamPietralla a9bef7b50d Migrate frontend to Nuxt 4 and Nuxt UI
- Upgrade to Nuxt 4 (sources under app/), add @nuxt/ui, Tailwind v4 and
  Lucide icons; drop @nuxtjs/tailwindcss
- Replace the custom Yale* components, Modal, Navbar and icon components with
  UButton/UInput/UModal/UTable/UCard/UHeader/UBadge/UAlert and toasts
- Add dark/light mode toggle and a logout button
- Add a useApi composable: central base URL/credentials, JSON-encoded bodies,
  error handling, and redirect to login when the session expires
- Fix modal listener leak, missing People heading, unhandled fetch errors and
  login redirect for already-authenticated users
- Make the code and people tables fit on phone screens
- Retake README screenshots
2026-11-16 12:23:31 +11:00

47 lines
1.6 KiB
TypeScript

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<boolean>('authenticated')
async function request<T>(path: string, method: 'GET' | 'POST' | 'DELETE' = 'GET', body?: unknown): Promise<ApiResponse<T>> {
try {
return await $fetch<ApiResponse<T>>(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<ApiResponse<T>>
// 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: <T>(path: string) => request<T>(path),
post: <T>(path: string, body?: unknown) => request<T>(path, 'POST', body),
delete: <T>(path: string) => request<T>(path, 'DELETE')
}
}