feat: add React + TypeScript frontend with Vite, routing, tests and Docker setup

M3 frontend infrastructure for the newzy news application:

- Vite + React 18 + TypeScript project (Node >=18) in frontend/
- React Router v6: BrowserRouter in App.tsx, routes for /, /articles,
  /articles/:id and /categories, Link/NavLink-based navigation
- lucide-react icons (Home, FileText, Settings, Search, ...) in the
  responsive Header (desktop + mobile menu) and article components
- Reusable components: ArticleCard, AuthorAvatar, CategoryBadge (CVA),
  Layout shell with backend API status indicator in the footer
- Typed API client (fetch wrapper, ApiError, endpoint helpers) with
  types matching the backend models; sample-data fallback until the
  backend article endpoints exist
- Tailwind CSS global/component styles, cn() helper (clsx + tailwind-merge)
- Unit tests: Vitest + React Testing Library (23 tests, 100% statement
  coverage on components)
- E2E tests: Playwright (9 tests) covering page shell, feed rendering,
  client-side navigation, article route and API interactions
- ESLint (react + react-hooks + typescript) configured and passing
- Multi-stage Dockerfile (Vite build -> Nginx) with SPA fallback and an
  /api/ proxy to the backend service; docker-compose frontend service on
  port 3000 in both frontend/ and the root docker-compose.yml
- README with setup, API documentation, testing and Docker instructions
This commit is contained in:
Daniel Samson committed 2026-10-30 14:10:29 +00:00
1 parent cbeac5e16b
commit ffe19272b3
45 files changed
+9843 -4

No files matched your search

+172
View File
@@ -0,0 +1,172 @@
/**
* 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';
export const API_BASE_URL: string =
(import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '/api/v1';
/** 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<RequestInit, 'body'> {
/** JSON-serializable request body (stringified automatically). */
body?: unknown;
}
/**
* Low-level fetch wrapper: prepends the base URL, sends JSON, parses the
* response and converts failures into `ApiError`.
*/
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const { body, headers, ...rest } = options;
let response: Response;
try {
response = await fetch(`${API_BASE_URL}${path}`, {
...rest,
headers: {
Accept: 'application/json',
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
...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) {
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: <T>(path: string, init?: RequestOptions) => request<T>(path, init),
post: <T>(path: string, body: unknown, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'POST', body }),
put: <T>(path: string, body: unknown, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'PUT', body }),
patch: <T>(path: string, body: unknown, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'PATCH', body }),
delete: <T>(path: string, init?: RequestOptions) =>
request<T>(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<HealthResponse> {
return api.get<HealthResponse>('/health');
}
/** `GET /api/v1/version` — application name and version. */
export function getVersion(): Promise<VersionResponse> {
return api.get<VersionResponse>('/version');
}
/**
* `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<Article[]> {
return api.get<BackendArticle[]>('/articles').then((articles) =>
articles.map(toArticle),
);
}