/** * Typed API client for the newzy backend. * * - Base URL: `/api/v1` by default (overridable via `VITE_API_BASE_URL`). * In development the Vite dev server proxies `/api` to * `http://localhost:8000` (see `vite.config.ts`); in Docker the Nginx * container proxies `/api/` to the `backend` service (see `nginx.conf`). * - All non-2xx responses throw `ApiError` carrying the backend's * standardized error envelope (`{ detail, code, errors? }`). */ import type { ApiErrorPayload, Article, Author, Category, HealthResponse, VersionResponse, } from '../types'; import type { MeResponse, TokenResponse } from '../types/auth'; export const API_BASE_URL: string = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '/api/v1'; /** localStorage key under which the JWT session token is persisted. */ export const TOKEN_KEY = 'AUTH_TOKEN'; /** Error thrown for failed API requests (network or non-2xx responses). */ export class ApiError extends Error { readonly status: number; readonly code?: string; constructor(status: number, message: string, code?: string) { super(message); this.name = 'ApiError'; this.status = status; this.code = code; } } interface RequestOptions extends Omit { /** JSON-serializable request body (stringified automatically). */ body?: unknown; /** Use this Bearer token instead of the one stored under TOKEN_KEY. */ token?: string; } /** * Low-level fetch wrapper: prepends the base URL, sends JSON, parses the * response and converts failures into `ApiError`. */ async function request(path: string, options: RequestOptions = {}): Promise { const { body, headers, token, ...rest } = options; let response: Response; try { // Attach the JWT (explicit override or the stored session) so the // backend can identify the caller on protected endpoints. const bearer = token ?? localStorage.getItem(TOKEN_KEY); response = await fetch(`${API_BASE_URL}${path}`, { ...rest, headers: { Accept: 'application/json', ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}), ...headers, }, body: body !== undefined ? JSON.stringify(body) : undefined, }); } catch { throw new ApiError(0, 'Network error: unable to reach the newzy API.', 'network_error'); } if (!response.ok) { // 401: the stored session is invalid/expired — drop it so the UI can // redirect to login instead of retrying with a dead token. if (response.status === 401) localStorage.removeItem(TOKEN_KEY); let payload: ApiErrorPayload | null = null; try { payload = (await response.json()) as ApiErrorPayload; } catch { // Non-JSON error body — fall back to the status line. } throw new ApiError( response.status, payload?.detail ?? `Request to ${path} failed with status ${response.status}.`, payload?.code, ); } if (response.status === 204) { return undefined as T; } return (await response.json()) as T; } /** Type-safe request helpers. */ export const api = { get: (path: string, init?: RequestOptions) => request(path, init), post: (path: string, body: unknown, init?: RequestOptions) => request(path, { ...init, method: 'POST', body }), put: (path: string, body: unknown, init?: RequestOptions) => request(path, { ...init, method: 'PUT', body }), patch: (path: string, body: unknown, init?: RequestOptions) => request(path, { ...init, method: 'PATCH', body }), delete: (path: string, init?: RequestOptions) => request(path, { ...init, method: 'DELETE' }), }; /* --- Backend wire formats (snake_case, see backend/schemas) ------------- */ interface BackendCategory { id: number; name: string; slug: string; } interface BackendAuthor { id: number; name: string; email: string; bio: string | null; } interface BackendArticle { id: number; title: string; content: string; author_id: number; category_id: number; created_at: string; published: boolean; author?: BackendAuthor; category?: BackendCategory; } function toCategory(category: BackendCategory): Category { return { id: category.id, name: category.name, slug: category.slug }; } function toAuthor(author: BackendAuthor): Author { return { id: author.id, name: author.name, email: author.email, bio: author.bio ?? undefined, }; } function toArticle(article: BackendArticle): Article { return { id: article.id, title: article.title, content: article.content, authorId: article.author_id, author: article.author ? toAuthor(article.author) : undefined, categoryId: article.category_id, category: article.category ? toCategory(article.category) : undefined, createdAt: article.created_at, published: article.published, }; } /* --- Typed endpoint helpers --------------------------------------------- */ /** `GET /api/v1/health` — service liveness probe. */ export function getHealth(): Promise { return api.get('/health'); } /** `GET /api/v1/version` — application name and version. */ export function getVersion(): Promise { return api.get('/version'); } /* --- Auth endpoints (JWT sessions, see `src/auth.tsx`) ------------------- */ /** `POST /api/v1/auth/register` — create an account; returns the JWT. */ export function register(username: string, password: string): Promise { return api.post('/auth/register', { username, password }); } /** `POST /api/v1/auth/login` — authenticate; returns the JWT. */ export function login(username: string, password: string): Promise { return api.post('/auth/login', { username, password }); } /** `GET /api/v1/auth/me` — current user for the explicit (or stored) token. */ export function me(token?: string): Promise { return api.get('/auth/me', token !== undefined ? { token } : undefined); } /** `POST /api/v1/auth/logout` — stateless; the client discards the token. */ export function logout(): Promise { return api.post('/auth/logout', undefined); } /** * `GET /api/v1/articles` — list of published articles. * * The endpoint is provided by a later backend milestone; until then the * UI falls back to sample data (see `src/data/sample.ts`). */ export function getArticles(): Promise { return api.get('/articles').then((articles) => articles.map(toArticle), ); }