Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ffe19272b3 | ||
|
|
cbeac5e16b | ||
|
|
ffdeb99fbe | ||
|
|
9a6f75ebd8 |
No files matched your search
@@ -8,14 +8,18 @@
|
|||||||
|
|
||||||
| Milestone | Description | Status |
|
| Milestone | Description | Status |
|
||||||
| --------- | ------------------------- | -------- |
|
| --------- | ------------------------- | -------- |
|
||||||
| M1 | Git project setup | Done |
|
| M1 | Git project setup | Done |
|
||||||
| M2+ | News application features | Planned |
|
| M2 | Backend setup (FastAPI) | Done |
|
||||||
|
| M3 | Frontend setup (React + Vite) | Done |
|
||||||
|
| M4+ | News application features | Planned |
|
||||||
|
|
||||||
See [milestones/](milestones/) for milestone prompts and progress tracking.
|
See [milestones/](milestones/) for milestone prompts and progress tracking.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
No runtime requirements yet (setup-only milestone). When development of the application begins, the toolchain will be documented here.
|
- **Backend** ([`backend/`](backend/)): Python 3.11+, FastAPI (see [backend/README.md](backend/README.md))
|
||||||
|
- **Frontend** ([`frontend/`](frontend/)): Node.js 18+ (see [frontend/README.md](frontend/README.md))
|
||||||
|
- **Docker** (optional): for the containerized setup via the root [`docker-compose.yml`](docker-compose.yml)
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
@@ -40,6 +44,18 @@ git push -u origin feature/<short-description>
|
|||||||
|
|
||||||
Full contribution guidelines, including branching, merging, and rebase workflows, are in [CONTRIBUTING.md](CONTRIBUTING.md).
|
Full contribution guidelines, including branching, merging, and rebase workflows, are in [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||||
|
|
||||||
|
## Running the application
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Full stack (backend :8000 + frontend :3000)
|
||||||
|
docker compose up --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Or run each half locally — see the component READMEs for details:
|
||||||
|
|
||||||
|
- [frontend/README.md](frontend/README.md) — `npm run dev` (port 5173)
|
||||||
|
- [backend/README.md](backend/README.md) — `uvicorn main:app --reload` (port 8000)
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
- [CONTRIBUTING.md](CONTRIBUTING.md) — how to contribute
|
- [CONTRIBUTING.md](CONTRIBUTING.md) — how to contribute
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Keep the image small: exclude dev-only files from the build context
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.egg-info/
|
||||||
|
.pytest_cache/
|
||||||
|
htmlcov/
|
||||||
|
.coverage
|
||||||
|
tests/
|
||||||
|
data/
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
.git/
|
||||||
|
.gitignore
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
|
README.md
|
||||||
|
pytest.ini
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Database connection string (SQLAlchemy URL).
|
||||||
|
# Default points at the data directory mounted as a Docker volume;
|
||||||
|
# for local runs outside Docker any writable path works.
|
||||||
|
DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||||
|
|
||||||
|
# Comma-separated list of origins allowed by CORS (frontend dev server etc.)
|
||||||
|
CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Python artifacts
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.egg-info/
|
||||||
|
|
||||||
|
# Environment files
|
||||||
|
.env
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# Local databases
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
|
data/
|
||||||
|
|
||||||
|
# Docker
|
||||||
|
.docker/
|
||||||
|
|
||||||
|
# OS files
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Editor / IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*~
|
||||||
|
|
||||||
|
# Testing / coverage
|
||||||
|
.coverage
|
||||||
|
htmlcov/
|
||||||
|
.pytest_cache/
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install dependencies first to leverage Docker layer caching
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
# Copy application code
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# SQLite database lives on a mounted volume (see docker-compose.yml)
|
||||||
|
VOLUME /app/data/db
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
# Run application
|
||||||
|
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
# newzy — Backend
|
||||||
|
|
||||||
|
FastAPI backend for the **newzy** news web application. This milestone (M2)
|
||||||
|
provides the API backbone: application factory, SQLite persistence via
|
||||||
|
SQLAlchemy, core ORM models (`Article`, `Author`, `Category`), Pydantic
|
||||||
|
schemas, standardized error handling, and a unit-tested, containerized
|
||||||
|
deployment path.
|
||||||
|
|
||||||
|
## Project structure
|
||||||
|
|
||||||
|
```
|
||||||
|
backend/
|
||||||
|
├── api/
|
||||||
|
│ └── v1/
|
||||||
|
│ └── __init__.py # /api/v1 routes (health, version)
|
||||||
|
├── core/
|
||||||
|
│ ├── __init__.py # re-exports create_app
|
||||||
|
│ └── app.py # app factory, CORS, global error handlers
|
||||||
|
├── db/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ └── session.py # engine, session factory, get_db dependency
|
||||||
|
├── models/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── base.py # declarative Base
|
||||||
|
│ ├── article.py # Article model
|
||||||
|
│ ├── author.py # Author model
|
||||||
|
│ └── category.py # Category model + slugify()
|
||||||
|
├── schemas/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── article.py # Article request/response schemas
|
||||||
|
│ ├── author.py # Author request/response schemas
|
||||||
|
│ ├── category.py # Category request/response schemas
|
||||||
|
│ └── common.py # Health/Version payloads, ErrorDetail envelope
|
||||||
|
├── tests/
|
||||||
|
│ ├── conftest.py # fixtures: per-test SQLite DB + TestClient
|
||||||
|
│ ├── test_health.py
|
||||||
|
│ ├── test_version.py
|
||||||
|
│ └── test_models.py
|
||||||
|
├── main.py # application entry point (uvicorn target)
|
||||||
|
├── config.py # env-driven settings (DATABASE_URL, CORS_ORIGINS)
|
||||||
|
├── requirements.txt
|
||||||
|
├── Dockerfile
|
||||||
|
├── .dockerignore
|
||||||
|
├── .env.example
|
||||||
|
├── .gitignore
|
||||||
|
└── pytest.ini
|
||||||
|
```
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
### 1. Local development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
uvicorn main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
The server starts on <http://localhost:8000>. Interactive API docs are
|
||||||
|
served at <http://localhost:8000/docs>.
|
||||||
|
|
||||||
|
The SQLite database file is created automatically at
|
||||||
|
`./data/db/newzy.db` (directory included) on first start.
|
||||||
|
|
||||||
|
### 2. With Docker Compose (from the repository root)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up --build
|
||||||
|
```
|
||||||
|
|
||||||
|
This builds the image, maps port `8000`, and persists the SQLite database in
|
||||||
|
`./data/db` on the host.
|
||||||
|
|
||||||
|
### 3. Run the tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
Coverage is reported per module (see `pytest.ini`). Tests run against a
|
||||||
|
throwaway SQLite file per test — the real database is never touched.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
All settings come from environment variables (see `.env.example`):
|
||||||
|
|
||||||
|
| Variable | Default | Description |
|
||||||
|
| --------------- | -------------------------------------- | ------------------------------------ |
|
||||||
|
| `DATABASE_URL` | `sqlite:///./data/db/newzy.db` | SQLAlchemy database URL |
|
||||||
|
| `CORS_ORIGINS` | `http://localhost:3000,http://127.0.0.1:3000` | Comma-separated allowed origins |
|
||||||
|
|
||||||
|
Inside the container the database lives at `/app/data/db/newzy.db` on the
|
||||||
|
mounted volume (see `docker-compose.yml` at the repository root).
|
||||||
|
|
||||||
|
## API endpoints
|
||||||
|
|
||||||
|
| Method | Path | Description |
|
||||||
|
| ------ | --------------- | -------------------------------------------- |
|
||||||
|
| GET | `/health` | Root health check |
|
||||||
|
| GET | `/api/v1/health`| Health check (versioned alternative path) |
|
||||||
|
| GET | `/api/v1/version` | Application name and version |
|
||||||
|
| GET | `/docs` | Interactive OpenAPI documentation (Swagger) |
|
||||||
|
| GET | `/api/v1/openapi.json` | OpenAPI schema |
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
Health check:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://localhost:8000/health
|
||||||
|
# {"status":"ok","version":"0.1.0"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Version:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://localhost:8000/api/v1/version
|
||||||
|
# {"app":"newzy","version":"0.1.0"}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Error format
|
||||||
|
|
||||||
|
All non-2xx responses use a standardized envelope:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"detail": "Not Found",
|
||||||
|
"code": "not_found"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Validation failures (HTTP 422) additionally include per-field errors:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"detail": "Request validation failed.",
|
||||||
|
"code": "validation_error",
|
||||||
|
"errors": [
|
||||||
|
{
|
||||||
|
"loc": ["body", "title"],
|
||||||
|
"msg": "String should have at least 1 character",
|
||||||
|
"type": "string_too_short"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| `code` | HTTP | Meaning |
|
||||||
|
| ----------------- | ---- | -------------------------------- |
|
||||||
|
| `bad_request` | 400 | Malformed request |
|
||||||
|
| `unauthorized` | 401 | Missing/invalid credentials |
|
||||||
|
| `forbidden` | 403 | Insufficient permissions |
|
||||||
|
| `not_found` | 404 | Resource does not exist |
|
||||||
|
| `method_not_allowed` | 405 | Method not allowed on resource |
|
||||||
|
| `conflict` | 409 | State conflict (e.g. duplicate) |
|
||||||
|
| `validation_error`| 422 | Request failed schema validation |
|
||||||
|
| `too_many_requests`| 429 | Rate limit exceeded |
|
||||||
|
| `internal_error` | 500 | Unhandled server error |
|
||||||
|
|
||||||
|
## Data model
|
||||||
|
|
||||||
|
```
|
||||||
|
Author 1 ──── * Article * ──── 1 Category
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Article**: `id`, `title` (unique, ≤200 chars), `content`, `author_id` (FK),
|
||||||
|
`category_id` (FK), `created_at`, `published` (default `false`)
|
||||||
|
- **Author**: `id`, `name` (unique, ≤100 chars), `email` (unique, ≤255 chars),
|
||||||
|
`bio` (nullable)
|
||||||
|
- **Category**: `id`, `name` (unique, ≤100 chars), `slug` (unique, ≤100 chars)
|
||||||
|
|
||||||
|
ORM relationships are defined on both sides (`author.articles`,
|
||||||
|
`category.articles`, `article.author`, `article.category`), and SQLite foreign
|
||||||
|
key enforcement is enabled via a `PRAGMA foreign_keys=ON` connection listener.
|
||||||
|
|
||||||
|
## Docker
|
||||||
|
|
||||||
|
The `Dockerfile` builds on `python:3.11-slim`, installs `requirements.txt`,
|
||||||
|
copies the application code, exposes port `8000`, and runs
|
||||||
|
`uvicorn main:app --host 0.0.0.0 --port 8000`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -t newzy-backend ./backend
|
||||||
|
docker run --rm -p 8000:8000 -v $(pwd)/data/db:/app/data/db \
|
||||||
|
-e DATABASE_URL=sqlite:///./data/db/newzy.db newzy-backend
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes & limitations
|
||||||
|
|
||||||
|
- SQLite is fine for development and demos; a production database
|
||||||
|
(e.g. Postgres) will be configured in a later milestone.
|
||||||
|
- No authentication, rate limiting, or pagination yet — those arrive with the
|
||||||
|
article CRUD milestones.
|
||||||
|
- CORS origins are configured for frontend development; validate them before
|
||||||
|
production deployment.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""API package (versioned route groups)."""
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""API v1 routes.
|
||||||
|
|
||||||
|
Mounted under ``/api/v1`` (see ``core.app.create_app``).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from config import APP_NAME, APP_VERSION
|
||||||
|
from schemas import HealthResponse, VersionResponse
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health", response_model=HealthResponse, summary="Service health check")
|
||||||
|
def get_health() -> HealthResponse:
|
||||||
|
"""Report service health (alternative path to the root ``/health``)."""
|
||||||
|
return HealthResponse(status="ok", version=APP_VERSION)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/version", response_model=VersionResponse, summary="Application version")
|
||||||
|
def get_version() -> VersionResponse:
|
||||||
|
"""Return the application name and version."""
|
||||||
|
return VersionResponse(app=APP_NAME, version=APP_VERSION)
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Application configuration.
|
||||||
|
|
||||||
|
Settings are read from environment variables so the same code runs
|
||||||
|
locally, in Docker (see ``docker-compose.yml``) and in CI.
|
||||||
|
See ``.env.example`` for the documented variable set.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
# --- Application metadata -------------------------------------------------
|
||||||
|
APP_NAME = "newzy"
|
||||||
|
APP_VERSION = "0.1.0"
|
||||||
|
API_V1_PREFIX = "/api/v1"
|
||||||
|
|
||||||
|
# Default location of the SQLite database file (relative to the working
|
||||||
|
# directory). In Docker this resolves inside the mounted volume
|
||||||
|
# (``./data/db`` -> ``/app/data/db`` on the host's ``./data/db``).
|
||||||
|
DEFAULT_DATABASE_URL = "sqlite:///./data/db/newzy.db"
|
||||||
|
|
||||||
|
# Default origins allowed by CORS (frontend dev servers).
|
||||||
|
DEFAULT_CORS_ORIGINS = "http://localhost:3000,http://127.0.0.1:3000"
|
||||||
|
|
||||||
|
|
||||||
|
class Settings:
|
||||||
|
"""Runtime settings loaded from the environment."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.database_url: str = os.getenv("DATABASE_URL", DEFAULT_DATABASE_URL)
|
||||||
|
self.cors_origins: list[str] = [
|
||||||
|
origin.strip()
|
||||||
|
for origin in os.getenv("CORS_ORIGINS", DEFAULT_CORS_ORIGINS).split(",")
|
||||||
|
if origin.strip()
|
||||||
|
]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_sqlite(self) -> bool:
|
||||||
|
"""True when the configured database is SQLite."""
|
||||||
|
return self.database_url.startswith("sqlite")
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
"""Return the cached application settings."""
|
||||||
|
return Settings()
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""Core package (application factory and global error handling)."""
|
||||||
|
|
||||||
|
from core.app import create_app
|
||||||
|
|
||||||
|
__all__ = ["create_app"]
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"""Application factory, CORS setup and global error handling.
|
||||||
|
|
||||||
|
Every non-2xx response uses the standardized envelope
|
||||||
|
(``schemas.common.ErrorDetail``)::
|
||||||
|
|
||||||
|
{"detail": "<human readable message>", "code": "<machine readable code>"}
|
||||||
|
|
||||||
|
with an additional ``errors`` array for validation failures (HTTP 422).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Request, status
|
||||||
|
from fastapi.encoders import jsonable_encoder
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
|
|
||||||
|
from api.v1 import router as api_v1_router
|
||||||
|
from config import API_V1_PREFIX, APP_NAME, APP_VERSION, get_settings
|
||||||
|
from db.session import engine
|
||||||
|
from models import Base
|
||||||
|
|
||||||
|
logger = logging.getLogger("newzy")
|
||||||
|
|
||||||
|
# Machine-readable codes for the most common HTTP errors.
|
||||||
|
_HTTP_ERROR_CODES: dict[int, str] = {
|
||||||
|
400: "bad_request",
|
||||||
|
401: "unauthorized",
|
||||||
|
403: "forbidden",
|
||||||
|
404: "not_found",
|
||||||
|
405: "method_not_allowed",
|
||||||
|
409: "conflict",
|
||||||
|
422: "validation_error",
|
||||||
|
429: "too_many_requests",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _error_response(status_code: int, detail: str, code: str, errors=None) -> JSONResponse:
|
||||||
|
"""Build the standardized error envelope as a JSON response."""
|
||||||
|
payload: dict = {"detail": detail, "code": code}
|
||||||
|
if errors is not None:
|
||||||
|
payload["errors"] = jsonable_encoder(errors)
|
||||||
|
return JSONResponse(status_code=status_code, content=payload)
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||||
|
"""Create database tables on startup (idempotent for SQLite volumes)."""
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
logger.info("Database tables ensured (engine: %s)", engine.url)
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def create_app() -> FastAPI:
|
||||||
|
"""Build and configure the FastAPI application."""
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title=APP_NAME,
|
||||||
|
version=APP_VERSION,
|
||||||
|
description="Backend API for the newzy news web application.",
|
||||||
|
openapi_url=f"{API_V1_PREFIX}/openapi.json",
|
||||||
|
lifespan=lifespan,
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- CORS (frontend development) ------------------------------------
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=settings.cors_origins,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- Global error handlers -------------------------------------------
|
||||||
|
@app.exception_handler(StarletteHTTPException)
|
||||||
|
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
||||||
|
code = _HTTP_ERROR_CODES.get(exc.status_code, "http_error")
|
||||||
|
return _error_response(exc.status_code, str(exc.detail), code)
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||||
|
return _error_response(
|
||||||
|
422,
|
||||||
|
"Request validation failed.",
|
||||||
|
"validation_error",
|
||||||
|
errors=exc.errors(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@app.exception_handler(Exception)
|
||||||
|
async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
logger.exception("Unhandled error processing %s %s", request.method, request.url.path)
|
||||||
|
return _error_response(
|
||||||
|
status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
|
"An unexpected error occurred.",
|
||||||
|
"internal_error",
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- Routes -----------------------------------------------------------
|
||||||
|
app.include_router(api_v1_router, prefix=API_V1_PREFIX, tags=["v1"])
|
||||||
|
|
||||||
|
@app.get("/health", tags=["health"], summary="Root health check")
|
||||||
|
async def health() -> dict:
|
||||||
|
"""Liveness probe (mirrors ``GET /api/v1/health``)."""
|
||||||
|
return {"status": "ok", "version": APP_VERSION}
|
||||||
|
|
||||||
|
return app
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Database package (engine, session management)."""
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""SQLAlchemy engine and session management.
|
||||||
|
|
||||||
|
The engine is created once at import time from ``config.get_settings()``.
|
||||||
|
For SQLite, the parent directory of the database file is created when it
|
||||||
|
does not exist yet (the Docker volume mount provides it in containers),
|
||||||
|
and the ``foreign_keys`` pragma is enabled on every connection because
|
||||||
|
SQLite has it disabled by default.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Generator
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine, event
|
||||||
|
from sqlalchemy.engine import Engine
|
||||||
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
|
from config import get_settings
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_sqlite_dir(database_url: str) -> None:
|
||||||
|
"""Create the parent directory of a file-based SQLite database."""
|
||||||
|
prefix = "sqlite:///"
|
||||||
|
if not database_url.startswith(prefix):
|
||||||
|
return
|
||||||
|
db_path = Path(database_url.removeprefix(prefix))
|
||||||
|
if not db_path.parts or db_path.name == ":memory:":
|
||||||
|
return
|
||||||
|
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
if settings.is_sqlite:
|
||||||
|
_ensure_sqlite_dir(settings.database_url)
|
||||||
|
connect_args: dict = {"check_same_thread": False}
|
||||||
|
else:
|
||||||
|
connect_args = {}
|
||||||
|
|
||||||
|
engine: Engine = create_engine(
|
||||||
|
settings.database_url,
|
||||||
|
connect_args=connect_args,
|
||||||
|
echo=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
if settings.is_sqlite:
|
||||||
|
|
||||||
|
@event.listens_for(engine, "connect")
|
||||||
|
def _enable_foreign_keys(dbapi_connection, _connection_record) -> None: # pragma: no cover
|
||||||
|
"""Enforce foreign key constraints (OFF by default in SQLite)."""
|
||||||
|
cursor = dbapi_connection.cursor()
|
||||||
|
cursor.execute("PRAGMA foreign_keys=ON")
|
||||||
|
cursor.close()
|
||||||
|
|
||||||
|
|
||||||
|
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||||
|
|
||||||
|
|
||||||
|
def get_db() -> Generator[Session, None, None]:
|
||||||
|
"""FastAPI dependency that yields a database session and always closes it."""
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
"""newzy backend entry point.
|
||||||
|
|
||||||
|
Run locally with:
|
||||||
|
|
||||||
|
uvicorn main:app --reload
|
||||||
|
"""
|
||||||
|
|
||||||
|
from core import create_app
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
"""SQLAlchemy ORM models for newzy."""
|
||||||
|
|
||||||
|
from models.article import Article
|
||||||
|
from models.author import Author
|
||||||
|
from models.base import Base
|
||||||
|
from models.category import Category, slugify
|
||||||
|
|
||||||
|
__all__ = ["Article", "Author", "Base", "Category", "slugify"]
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""Article model."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from models.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
def _utcnow() -> datetime:
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
class Article(Base):
|
||||||
|
"""A news article written by an author and filed under a category."""
|
||||||
|
|
||||||
|
__tablename__ = "articles"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
title: Mapped[str] = mapped_column(String(200), unique=True, nullable=False, index=True)
|
||||||
|
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
author_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey("authors.id"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
category_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey("categories.id"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), default=_utcnow, nullable=False
|
||||||
|
)
|
||||||
|
published: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
|
|
||||||
|
author: Mapped[Author] = relationship(back_populates="articles")
|
||||||
|
category: Mapped[Category] = relationship(back_populates="articles")
|
||||||
|
|
||||||
|
def __repr__(self) -> str: # pragma: no cover
|
||||||
|
return f"<Article id={self.id} title={self.title!r}>"
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""Author model."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from sqlalchemy import String, Text
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from models.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Author(Base):
|
||||||
|
"""A person who writes articles."""
|
||||||
|
|
||||||
|
__tablename__ = "authors"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
name: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
|
||||||
|
email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
|
||||||
|
bio: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
|
||||||
|
articles: Mapped[list[Article]] = relationship(back_populates="author")
|
||||||
|
|
||||||
|
def __repr__(self) -> str: # pragma: no cover
|
||||||
|
return f"<Author id={self.id} name={self.name!r}>"
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
"""Declarative base shared by all ORM models."""
|
||||||
|
|
||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
"""Base class for all newzy ORM models."""
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""Category model."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
|
||||||
|
from sqlalchemy import String
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from models.base import Base
|
||||||
|
|
||||||
|
_SLUG_RE = re.compile(r"[^a-z0-9]+")
|
||||||
|
|
||||||
|
|
||||||
|
def slugify(text: str) -> str:
|
||||||
|
"""Convert an arbitrary string into a URL-friendly slug.
|
||||||
|
|
||||||
|
>>> slugify("Technology & Science")
|
||||||
|
'technology-science'
|
||||||
|
>>> slugify(" Sports ")
|
||||||
|
'sports'
|
||||||
|
"""
|
||||||
|
normalized = unicodedata.normalize("NFKD", text)
|
||||||
|
normalized = normalized.encode("ascii", "ignore").decode("ascii")
|
||||||
|
return _SLUG_RE.sub("-", normalized.lower()).strip("-")
|
||||||
|
|
||||||
|
|
||||||
|
class Category(Base):
|
||||||
|
"""A topic used to group articles."""
|
||||||
|
|
||||||
|
__tablename__ = "categories"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
name: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
|
||||||
|
slug: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
|
||||||
|
|
||||||
|
articles: Mapped[list[Article]] = relationship(back_populates="category")
|
||||||
|
|
||||||
|
def __repr__(self) -> str: # pragma: no cover
|
||||||
|
return f"<Category id={self.id} slug={self.slug!r}>"
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[pytest]
|
||||||
|
testpaths = tests
|
||||||
|
python_files = test_*.py
|
||||||
|
python_classes = Test*
|
||||||
|
python_functions = test_*
|
||||||
|
asyncio_mode = auto
|
||||||
|
addopts = -v --cov=. --cov-report=term-missing
|
||||||
|
pythonpath = .
|
||||||
|
filterwarnings = ignore::DeprecationWarning
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# --- Web framework --------------------------------------------------------
|
||||||
|
fastapi>=0.116
|
||||||
|
uvicorn>=0.35
|
||||||
|
|
||||||
|
# --- Database -------------------------------------------------------------
|
||||||
|
SQLAlchemy>=2.0.41
|
||||||
|
|
||||||
|
# --- Schemas / validation ---------------------------------------------------
|
||||||
|
pydantic>=2.11
|
||||||
|
|
||||||
|
# --- Misc runtime -----------------------------------------------------------
|
||||||
|
python-multipart>=0.0.20
|
||||||
|
|
||||||
|
# --- Testing ----------------------------------------------------------------
|
||||||
|
pytest>=8.3
|
||||||
|
pytest-asyncio>=0.25
|
||||||
|
pytest-cov>=6.0
|
||||||
|
# httpx is required by fastapi.testclient.TestClient
|
||||||
|
httpx>=0.28
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""Pydantic request/response schemas for newzy."""
|
||||||
|
|
||||||
|
from schemas.article import ArticleBase, ArticleCreate, ArticleRead, ArticleUpdate
|
||||||
|
from schemas.author import AuthorBase, AuthorCreate, AuthorRead, AuthorUpdate
|
||||||
|
from schemas.category import CategoryBase, CategoryCreate, CategoryRead, CategoryUpdate
|
||||||
|
from schemas.common import ErrorDetail, HealthResponse, VersionResponse
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ArticleBase",
|
||||||
|
"ArticleCreate",
|
||||||
|
"ArticleRead",
|
||||||
|
"ArticleUpdate",
|
||||||
|
"AuthorBase",
|
||||||
|
"AuthorCreate",
|
||||||
|
"AuthorRead",
|
||||||
|
"AuthorUpdate",
|
||||||
|
"CategoryBase",
|
||||||
|
"CategoryCreate",
|
||||||
|
"CategoryRead",
|
||||||
|
"CategoryUpdate",
|
||||||
|
"ErrorDetail",
|
||||||
|
"HealthResponse",
|
||||||
|
"VersionResponse",
|
||||||
|
]
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Schemas for the Article model."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
|
||||||
|
class ArticleBase(BaseModel):
|
||||||
|
"""Fields shared by create/update/read article schemas."""
|
||||||
|
|
||||||
|
title: str = Field(..., min_length=1, max_length=200)
|
||||||
|
content: str = Field(..., min_length=1)
|
||||||
|
|
||||||
|
|
||||||
|
class ArticleCreate(ArticleBase):
|
||||||
|
"""Payload for creating an article."""
|
||||||
|
|
||||||
|
author_id: int = Field(..., ge=1)
|
||||||
|
category_id: int = Field(..., ge=1)
|
||||||
|
published: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class ArticleUpdate(BaseModel):
|
||||||
|
"""Payload for updating an article (all fields optional)."""
|
||||||
|
|
||||||
|
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||||
|
content: str | None = Field(default=None, min_length=1)
|
||||||
|
author_id: int | None = Field(default=None, ge=1)
|
||||||
|
category_id: int | None = Field(default=None, ge=1)
|
||||||
|
published: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ArticleRead(BaseModel):
|
||||||
|
"""Article as returned by the API."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
title: str
|
||||||
|
content: str
|
||||||
|
author_id: int
|
||||||
|
category_id: int
|
||||||
|
created_at: datetime
|
||||||
|
published: bool
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Schemas for the Author model."""
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorBase(BaseModel):
|
||||||
|
"""Fields shared by create/update/read author schemas."""
|
||||||
|
|
||||||
|
name: str = Field(..., min_length=1, max_length=100)
|
||||||
|
email: str = Field(..., min_length=3, max_length=255)
|
||||||
|
bio: str | None = None
|
||||||
|
|
||||||
|
@field_validator("email")
|
||||||
|
@classmethod
|
||||||
|
def _valid_email(cls, value: str) -> str:
|
||||||
|
if "@" not in value or value.startswith("@") or value.endswith("@"):
|
||||||
|
raise ValueError("must be a valid email address")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorCreate(AuthorBase):
|
||||||
|
"""Payload for creating an author."""
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorUpdate(BaseModel):
|
||||||
|
"""Payload for updating an author (all fields optional)."""
|
||||||
|
|
||||||
|
name: str | None = Field(default=None, min_length=1, max_length=100)
|
||||||
|
email: str | None = Field(default=None, min_length=3, max_length=255)
|
||||||
|
bio: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorRead(AuthorBase):
|
||||||
|
"""Author as returned by the API."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Schemas for the Category model."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
from models.category import slugify
|
||||||
|
|
||||||
|
_SLUG_PATTERN = r"^[a-z0-9]+(?:-[a-z0-9]+)*$"
|
||||||
|
|
||||||
|
|
||||||
|
class CategoryBase(BaseModel):
|
||||||
|
"""Fields shared by category schemas."""
|
||||||
|
|
||||||
|
name: str = Field(..., min_length=1, max_length=100)
|
||||||
|
slug: str | None = Field(
|
||||||
|
default=None,
|
||||||
|
min_length=1,
|
||||||
|
max_length=100,
|
||||||
|
pattern=_SLUG_PATTERN,
|
||||||
|
description="URL-friendly identifier; derived from `name` when omitted.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class CategoryCreate(CategoryBase):
|
||||||
|
"""Payload for creating a category.
|
||||||
|
|
||||||
|
When ``slug`` is omitted it is generated from ``name``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class CategoryUpdate(BaseModel):
|
||||||
|
"""Payload for updating a category (all fields optional)."""
|
||||||
|
|
||||||
|
name: str | None = Field(default=None, min_length=1, max_length=100)
|
||||||
|
slug: str | None = Field(default=None, min_length=1, max_length=100, pattern=_SLUG_PATTERN)
|
||||||
|
|
||||||
|
|
||||||
|
class CategoryRead(BaseModel):
|
||||||
|
"""Category as returned by the API."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
name: str
|
||||||
|
slug: str
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_slug(create: CategoryCreate) -> str:
|
||||||
|
"""Resolve the slug to store: explicit slug or one derived from the name."""
|
||||||
|
return create.slug if create.slug is not None else slugify(create.name)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Shared response schemas and the standardized error envelope."""
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class ErrorDetail(BaseModel):
|
||||||
|
"""Standard error payload returned for all non-2xx responses.
|
||||||
|
|
||||||
|
``errors`` is only present for validation failures (HTTP 422) and
|
||||||
|
carries the per-field details.
|
||||||
|
"""
|
||||||
|
|
||||||
|
detail: str
|
||||||
|
code: str
|
||||||
|
errors: list[dict] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class HealthResponse(BaseModel):
|
||||||
|
"""Payload of the health check endpoints."""
|
||||||
|
|
||||||
|
status: str = "ok"
|
||||||
|
version: str
|
||||||
|
|
||||||
|
|
||||||
|
class VersionResponse(BaseModel):
|
||||||
|
"""Payload of the version endpoint."""
|
||||||
|
|
||||||
|
app: str
|
||||||
|
version: str
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Shared pytest fixtures for the newzy backend test suite.
|
||||||
|
|
||||||
|
The application is pointed at a throwaway SQLite file *before* it is
|
||||||
|
imported, so the module-level engine created in ``db.session`` never
|
||||||
|
touches the real database.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from sqlalchemy import Engine, create_engine, event
|
||||||
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
|
# --- Point the application at a temporary database before import ---------
|
||||||
|
_TMP_DB_FD, _TMP_DB_PATH = tempfile.mkstemp(suffix=".db")
|
||||||
|
os.close(_TMP_DB_FD)
|
||||||
|
os.environ["DATABASE_URL"] = f"sqlite:///{_TMP_DB_PATH}"
|
||||||
|
|
||||||
|
from db.session import get_db # noqa: E402
|
||||||
|
from main import app # noqa: E402
|
||||||
|
from models import Base # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _enable_foreign_keys(dbapi_connection, _connection_record) -> None:
|
||||||
|
"""Mirror the FK pragma applied to the production engine (see db.session)."""
|
||||||
|
cursor = dbapi_connection.cursor()
|
||||||
|
cursor.execute("PRAGMA foreign_keys=ON")
|
||||||
|
cursor.close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def engine() -> Iterator[Engine]:
|
||||||
|
"""A fresh SQLite database per test (created and destroyed around it)."""
|
||||||
|
fd, path = tempfile.mkstemp(suffix=".db")
|
||||||
|
os.close(fd)
|
||||||
|
test_engine = create_engine(
|
||||||
|
f"sqlite:///{path}", connect_args={"check_same_thread": False}
|
||||||
|
)
|
||||||
|
event.listen(test_engine, "connect", _enable_foreign_keys)
|
||||||
|
Base.metadata.create_all(test_engine)
|
||||||
|
try:
|
||||||
|
yield test_engine
|
||||||
|
finally:
|
||||||
|
test_engine.dispose()
|
||||||
|
Path(path).unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def session(engine: Engine) -> Iterator[Session]:
|
||||||
|
"""A SQLAlchemy session bound to the per-test database."""
|
||||||
|
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||||
|
db = TestingSession()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def client(engine: Engine) -> Iterator[TestClient]:
|
||||||
|
"""A FastAPI TestClient whose ``get_db`` dependency is overridden per test."""
|
||||||
|
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||||
|
|
||||||
|
def override_get_db() -> Iterator[Session]:
|
||||||
|
db = TestingSession()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
app.dependency_overrides[get_db] = override_get_db
|
||||||
|
with TestClient(app) as test_client:
|
||||||
|
yield test_client
|
||||||
|
app.dependency_overrides.clear()
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Tests for the health check endpoints."""
|
||||||
|
|
||||||
|
|
||||||
|
def test_health_returns_200_ok(client) -> None:
|
||||||
|
response = client.get("/health")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_health_returns_expected_json_structure(client) -> None:
|
||||||
|
payload = client.get("/health").json()
|
||||||
|
assert payload["status"] == "ok"
|
||||||
|
assert "version" in payload
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_v1_health_returns_200_ok(client) -> None:
|
||||||
|
"""The alternative health path ``/api/v1/health`` must behave the same."""
|
||||||
|
response = client.get("/api/v1/health")
|
||||||
|
assert response.status_code == 200
|
||||||
|
payload = response.json()
|
||||||
|
assert payload["status"] == "ok"
|
||||||
|
assert "version" in payload
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_route_returns_standardized_error(client) -> None:
|
||||||
|
response = client.get("/api/v1/does-not-exist")
|
||||||
|
assert response.status_code == 404
|
||||||
|
payload = response.json()
|
||||||
|
assert payload["code"] == "not_found"
|
||||||
|
assert "detail" in payload
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""Tests for ORM model instantiation and database operations."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
|
||||||
|
from models import Article, Author, Category, slugify
|
||||||
|
|
||||||
|
|
||||||
|
class TestAuthor:
|
||||||
|
def test_create_and_commit(self, session) -> None:
|
||||||
|
author = Author(
|
||||||
|
name="Ada Lovelace", email="ada@example.com", bio="First programmer."
|
||||||
|
)
|
||||||
|
session.add(author)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(author)
|
||||||
|
assert author.id is not None
|
||||||
|
assert session.get(Author, author.id).email == "ada@example.com"
|
||||||
|
|
||||||
|
def test_unique_name_enforced(self, session) -> None:
|
||||||
|
session.add(Author(name="Grace Hopper", email="grace@example.com"))
|
||||||
|
session.commit()
|
||||||
|
session.add(Author(name="Grace Hopper", email="other@example.com"))
|
||||||
|
with pytest.raises(IntegrityError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
|
||||||
|
def test_unique_email_enforced(self, session) -> None:
|
||||||
|
session.add(Author(name="Grace Hopper", email="grace@example.com"))
|
||||||
|
session.commit()
|
||||||
|
session.add(Author(name="Another Person", email="grace@example.com"))
|
||||||
|
with pytest.raises(IntegrityError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
|
||||||
|
def test_bio_is_nullable(self, session) -> None:
|
||||||
|
author = Author(name="Alan Turing", email="alan@example.com")
|
||||||
|
session.add(author)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(author)
|
||||||
|
assert author.bio is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestCategory:
|
||||||
|
def test_create_and_commit(self, session) -> None:
|
||||||
|
category = Category(name="Technology", slug="technology")
|
||||||
|
session.add(category)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(category)
|
||||||
|
assert category.id is not None
|
||||||
|
assert session.get(Category, category.id).name == "Technology"
|
||||||
|
|
||||||
|
def test_unique_name_enforced(self, session) -> None:
|
||||||
|
session.add(Category(name="Science", slug="science"))
|
||||||
|
session.commit()
|
||||||
|
session.add(Category(name="Science", slug="science-2"))
|
||||||
|
with pytest.raises(IntegrityError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
|
||||||
|
def test_unique_slug_enforced(self, session) -> None:
|
||||||
|
session.add(Category(name="Science", slug="science"))
|
||||||
|
session.commit()
|
||||||
|
session.add(Category(name="Science News", slug="science"))
|
||||||
|
with pytest.raises(IntegrityError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
|
||||||
|
def test_slug_generation(self) -> None:
|
||||||
|
assert slugify("Technology & Science") == "technology-science"
|
||||||
|
assert slugify(" Sports ") == "sports"
|
||||||
|
assert slugify("Already-fine") == "already-fine"
|
||||||
|
assert slugify("Café News") == "cafe-news"
|
||||||
|
|
||||||
|
|
||||||
|
class TestArticle:
|
||||||
|
def _make_author_category(self, session) -> tuple[Author, Category]:
|
||||||
|
author = Author(name="Byline Writer", email="writer@example.com")
|
||||||
|
category = Category(name="World", slug="world")
|
||||||
|
session.add_all([author, category])
|
||||||
|
session.commit()
|
||||||
|
session.refresh(author)
|
||||||
|
session.refresh(category)
|
||||||
|
return author, category
|
||||||
|
|
||||||
|
def test_create_and_commit(self, session) -> None:
|
||||||
|
author, category = self._make_author_category(session)
|
||||||
|
article = Article(
|
||||||
|
title="First post",
|
||||||
|
content="Hello world.",
|
||||||
|
author_id=author.id,
|
||||||
|
category_id=category.id,
|
||||||
|
)
|
||||||
|
session.add(article)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(article)
|
||||||
|
assert article.id is not None
|
||||||
|
assert article.created_at is not None
|
||||||
|
assert article.published is False
|
||||||
|
|
||||||
|
def test_foreign_key_relationships(self, session) -> None:
|
||||||
|
author, category = self._make_author_category(session)
|
||||||
|
article = Article(
|
||||||
|
title="Related",
|
||||||
|
content="Body text.",
|
||||||
|
author_id=author.id,
|
||||||
|
category_id=category.id,
|
||||||
|
)
|
||||||
|
session.add(article)
|
||||||
|
session.commit()
|
||||||
|
assert article.author.name == author.name
|
||||||
|
assert article.category.slug == "world"
|
||||||
|
assert article in author.articles
|
||||||
|
assert article in category.articles
|
||||||
|
|
||||||
|
def test_unique_title_enforced(self, session) -> None:
|
||||||
|
author, category = self._make_author_category(session)
|
||||||
|
session.add(
|
||||||
|
Article(title="Dup", content="one", author_id=author.id, category_id=category.id)
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
session.add(
|
||||||
|
Article(title="Dup", content="two", author_id=author.id, category_id=category.id)
|
||||||
|
)
|
||||||
|
with pytest.raises(IntegrityError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
|
||||||
|
def test_foreign_key_enforced(self, session) -> None:
|
||||||
|
author, category = self._make_author_category(session)
|
||||||
|
article = Article(
|
||||||
|
title="Orphan", content="No such author.", author_id=9999, category_id=category.id
|
||||||
|
)
|
||||||
|
session.add(article)
|
||||||
|
with pytest.raises(IntegrityError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Tests for the version endpoint."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
_SEMVER = re.compile(r"^\d+\.\d+\.\d+$")
|
||||||
|
|
||||||
|
|
||||||
|
def test_version_returns_200_ok(client) -> None:
|
||||||
|
response = client.get("/api/v1/version")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_version_response_format(client) -> None:
|
||||||
|
payload = client.get("/api/v1/version").json()
|
||||||
|
assert payload["app"] == "newzy"
|
||||||
|
assert _SEMVER.match(payload["version"]), f"unexpected version format: {payload['version']}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_version_matches_configured_app_version(client) -> None:
|
||||||
|
from config import APP_VERSION
|
||||||
|
|
||||||
|
payload = client.get("/api/v1/version").json()
|
||||||
|
assert payload["version"] == APP_VERSION
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
services:
|
||||||
|
backend:
|
||||||
|
build: ./backend
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
volumes:
|
||||||
|
- ./data/db:/app/data/db
|
||||||
|
environment:
|
||||||
|
- DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
restart: unless-stopped
|
||||||
|
frontend:
|
||||||
|
build: ./frontend
|
||||||
|
ports:
|
||||||
|
- "3000:80"
|
||||||
|
depends_on:
|
||||||
|
backend:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
/* ESLint configuration for the newzy frontend.
|
||||||
|
*
|
||||||
|
* Covers:
|
||||||
|
* - core ESLint recommended rules
|
||||||
|
* - TypeScript (@typescript-eslint recommended)
|
||||||
|
* - React (eslint-plugin-react recommended)
|
||||||
|
* - React Hooks (eslint-plugin-react-hooks)
|
||||||
|
*
|
||||||
|
* React Router best practices are enforced by convention + review (see
|
||||||
|
* README.md):
|
||||||
|
* - use react-router-dom <Link>/<NavLink> for in-app navigation (never
|
||||||
|
* plain <a> tags) so navigation stays client-side
|
||||||
|
* - use useParams/useSearchParams for dynamic segments
|
||||||
|
* - route definitions live in src/App.tsx only
|
||||||
|
*/
|
||||||
|
module.exports = {
|
||||||
|
root: true,
|
||||||
|
env: {
|
||||||
|
browser: true,
|
||||||
|
es2022: true,
|
||||||
|
node: true,
|
||||||
|
},
|
||||||
|
parser: '@typescript-eslint/parser',
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
sourceType: 'module',
|
||||||
|
ecmaFeatures: { jsx: true },
|
||||||
|
},
|
||||||
|
plugins: ['@typescript-eslint', 'react', 'react-hooks'],
|
||||||
|
extends: [
|
||||||
|
'eslint:recommended',
|
||||||
|
'plugin:@typescript-eslint/recommended',
|
||||||
|
'plugin:react/recommended',
|
||||||
|
'plugin:react-hooks/recommended',
|
||||||
|
],
|
||||||
|
settings: {
|
||||||
|
react: { version: 'detect' },
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
// TypeScript provides prop typing — no need for JS prop types.
|
||||||
|
'react/prop-types': 'off',
|
||||||
|
// React 17+ JSX transform — no need to import React for JSX.
|
||||||
|
'react/react-in-jsx-scope': 'off',
|
||||||
|
// Router navigation must never open new tabs by accident.
|
||||||
|
'react/jsx-no-target-blank': 'error',
|
||||||
|
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
|
||||||
|
},
|
||||||
|
ignorePatterns: [
|
||||||
|
'dist/',
|
||||||
|
'node_modules/',
|
||||||
|
'coverage/',
|
||||||
|
'playwright-report/',
|
||||||
|
'test-results/',
|
||||||
|
'playwright/.cache/',
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
.pnp
|
||||||
|
.pnp.js
|
||||||
|
|
||||||
|
# Builds / output
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
out/
|
||||||
|
|
||||||
|
# Environment files (never commit secrets)
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
|
||||||
|
# Testing artifacts
|
||||||
|
coverage/
|
||||||
|
.nyc_output/
|
||||||
|
playwright-report/
|
||||||
|
test-results/
|
||||||
|
playwright/.cache/
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
|
||||||
|
# Editor / IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
.project
|
||||||
|
.classpath
|
||||||
|
.settings/
|
||||||
|
|
||||||
|
# OS files
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
# --- Stage 1: build the production bundle ---------------------------------
|
||||||
|
FROM node:20-alpine AS build
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install dependencies first to leverage Docker layer caching.
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
# Copy application source and build.
|
||||||
|
COPY . .
|
||||||
|
ARG VITE_API_BASE_URL=/api/v1
|
||||||
|
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# --- Stage 2: serve static files with Nginx --------------------------------
|
||||||
|
FROM nginx:1.27-alpine
|
||||||
|
|
||||||
|
# SPA + API proxy configuration (proxies /api/ to the backend service).
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
# Production bundle from the build stage.
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
|
||||||
|
CMD wget -qO- http://localhost/ >/dev/null 2>&1 || exit 1
|
||||||
|
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
# newzy — Frontend
|
||||||
|
|
||||||
|
React + TypeScript frontend for the **newzy** news web application, built with
|
||||||
|
[Vite](https://vitejs.dev/), styled with [Tailwind CSS](https://tailwindcss.com/),
|
||||||
|
icons from [lucide-react](https://lucide.dev/), client-side routing via
|
||||||
|
[React Router v6](https://reactrouter.com/), unit-tested with
|
||||||
|
[Vitest](https://vitest.dev/) + React Testing Library, and E2E-tested with
|
||||||
|
[Playwright](https://playwright.dev/).
|
||||||
|
|
||||||
|
> Infrastructure milestone (M3): project structure, routing, types, reusable
|
||||||
|
> components, API client and testing setup. Complex UI features arrive in
|
||||||
|
> later milestones.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- **Node.js 18 or later** (Node 20+ recommended)
|
||||||
|
- npm 9+ (ships with Node 20)
|
||||||
|
- Optional: a running [backend](../backend/) on `http://localhost:8000`
|
||||||
|
(the UI falls back to sample data when the API is unavailable)
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Install dependencies
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 2. Start the dev server (http://localhost:5173)
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
The Vite dev server proxies `/api` to `http://localhost:8000`, so no CORS
|
||||||
|
configuration is needed during development.
|
||||||
|
|
||||||
|
## Scripts
|
||||||
|
|
||||||
|
| Script | Description |
|
||||||
|
| --------------------- | -------------------------------------------------------- |
|
||||||
|
| `npm run dev` | Start the Vite dev server with HMR on port 5173 |
|
||||||
|
| `npm run build` | Type-check (`tsc`) and build the production bundle to `dist/` |
|
||||||
|
| `npm run preview` | Serve the production build locally (port 4173) |
|
||||||
|
| `npm test` | Run unit tests once (Vitest) |
|
||||||
|
| `npm run test:watch` | Run unit tests in watch mode |
|
||||||
|
| `npm run test:coverage` | Run unit tests with coverage report |
|
||||||
|
| `npm run e2e` | Build the app and run Playwright E2E tests |
|
||||||
|
| `npm run e2e:ui` | Run Playwright E2E tests in the interactive UI |
|
||||||
|
| `npm run lint` | Lint the codebase with ESLint |
|
||||||
|
|
||||||
|
## Project structure
|
||||||
|
|
||||||
|
```
|
||||||
|
frontend/
|
||||||
|
├── index.html # Vite entry HTML (must live at the project root)
|
||||||
|
├── public/ # Static assets served as-is (favicon, robots.txt)
|
||||||
|
├── src/
|
||||||
|
│ ├── assets/
|
||||||
|
│ │ ├── logo.svg # Brand logo (placeholder)
|
||||||
|
│ │ └── styles/globals.css # Tailwind + global/component styles
|
||||||
|
│ ├── components/
|
||||||
|
│ │ ├── ui/ # Generic UI (lucide icons + router links)
|
||||||
|
│ │ │ ├── Header.tsx # Navigation header (desktop + mobile menu)
|
||||||
|
│ │ │ └── Layout.tsx # Page shell: header, <main>, footer, API status
|
||||||
|
│ │ └── articles/ # Domain-specific components
|
||||||
|
│ │ ├── ArticleCard.tsx # Article preview (thumb, title, author, badge)
|
||||||
|
│ │ ├── AuthorAvatar.tsx # Initials/profile image with name tooltip
|
||||||
|
│ │ └── CategoryBadge.tsx # Color-coded category pill (CVA variants)
|
||||||
|
│ ├── pages/ # Page-level components (one per route)
|
||||||
|
│ │ ├── Home.tsx # Featured article, search bar, article grid
|
||||||
|
│ │ ├── ArticlePage.tsx # /articles and /articles/:id placeholders
|
||||||
|
│ │ └── CategoriesPage.tsx # /categories listing placeholder
|
||||||
|
│ ├── api/
|
||||||
|
│ │ └── client.ts # Typed fetch wrapper + endpoint helpers
|
||||||
|
│ ├── data/
|
||||||
|
│ │ └── sample.ts # Sample feed (fallback until backend endpoints exist)
|
||||||
|
│ ├── lib/
|
||||||
|
│ │ └── utils.ts # cn() — clsx + tailwind-merge helper
|
||||||
|
│ ├── types/
|
||||||
|
│ │ └── index.ts # Article / Author / Category / API types
|
||||||
|
│ ├── tests/ # Unit tests (Vitest + React Testing Library)
|
||||||
|
│ │ ├── Header.test.tsx
|
||||||
|
│ │ ├── ArticleCard.test.tsx
|
||||||
|
│ │ ├── Layout.test.tsx
|
||||||
|
│ │ └── components/
|
||||||
|
│ ├── App.tsx # BrowserRouter + route definitions
|
||||||
|
│ └── main.tsx # React entry point
|
||||||
|
├── playwright/
|
||||||
|
│ └── e2e/ # Playwright E2E tests
|
||||||
|
│ ├── home.spec.ts # Shell, feed rendering, client-side navigation
|
||||||
|
│ └── api.spec.ts # API interactions (mocked endpoints)
|
||||||
|
├── Dockerfile # Multi-stage build: Vite build -> Nginx
|
||||||
|
├── nginx.conf # SPA fallback + /api/ proxy to the backend
|
||||||
|
├── docker-compose.yml # Standalone frontend (+backend) service config
|
||||||
|
├── vite.config.ts # Dev server (5173), /api proxy, build output
|
||||||
|
├── vitest.config.ts # Unit test config (jsdom)
|
||||||
|
├── playwright.config.ts # E2E config (chromium, vite preview webServer)
|
||||||
|
└── tailwind.config.js # Tailwind content scan + theme
|
||||||
|
```
|
||||||
|
|
||||||
|
### pages/ vs components/
|
||||||
|
|
||||||
|
- **`src/pages/`** — one component per route; owns page-level state and is
|
||||||
|
imported only by the router in `App.tsx`.
|
||||||
|
- **`src/components/`** — reusable UI. `ui/` holds generic building blocks
|
||||||
|
(header, layout) with lucide icons; `articles/` holds domain components.
|
||||||
|
|
||||||
|
## Routing (React Router v6)
|
||||||
|
|
||||||
|
Routes are defined in [`src/App.tsx`](src/App.tsx) with `BrowserRouter` at the
|
||||||
|
root. In-app navigation always uses `<Link>`/`<NavLink>` from
|
||||||
|
`react-router-dom` — **never plain anchor tags** — so navigation stays
|
||||||
|
client-side without page reloads.
|
||||||
|
|
||||||
|
| Path | Page component | Notes |
|
||||||
|
| -------------- | ------------------ | -------------------------------------- |
|
||||||
|
| `/` | `Home` | Feed, featured article, search bar |
|
||||||
|
| `/articles` | `ArticlePage` | "All articles" placeholder |
|
||||||
|
| `/articles/:id`| `ArticlePage` | Single article placeholder (`useParams`) |
|
||||||
|
| `/categories` | `CategoriesPage` | Category listing placeholder |
|
||||||
|
| `*` | `NotFound` (404) | Fallback route |
|
||||||
|
|
||||||
|
## API client
|
||||||
|
|
||||||
|
[`src/api/client.ts`](src/api/client.ts) wraps `fetch`:
|
||||||
|
|
||||||
|
- Base URL: `/api/v1` (override with the `VITE_API_BASE_URL` env var).
|
||||||
|
- Sends `Accept: application/json`; JSON-serializes request bodies.
|
||||||
|
- Non-2xx responses throw `ApiError` with the backend's standardized error
|
||||||
|
envelope (`{ detail, code, errors? }`).
|
||||||
|
- Typed endpoint helpers: `getHealth()`, `getVersion()`, `getArticles()`
|
||||||
|
(backend snake_case payloads are mapped onto the camelCase types in
|
||||||
|
`src/types/`).
|
||||||
|
|
||||||
|
### Backend endpoints (M2)
|
||||||
|
|
||||||
|
| Method | Path | Description |
|
||||||
|
| ------ | ---------------- | ------------------------------------ |
|
||||||
|
| GET | `/health` | Root liveness probe |
|
||||||
|
| GET | `/api/v1/health` | Service health (`status`, `version`) |
|
||||||
|
| GET | `/api/v1/version`| Application name and version |
|
||||||
|
|
||||||
|
Article/author/category endpoints are planned for a later backend milestone;
|
||||||
|
until then the home page renders the sample feed from
|
||||||
|
`src/data/sample.ts` (clearly labelled in the UI).
|
||||||
|
|
||||||
|
### How `/api` resolves per environment
|
||||||
|
|
||||||
|
| Environment | Mechanism |
|
||||||
|
| ------------------ | ---------------------------------------------------------------- |
|
||||||
|
| Dev (`npm run dev`) | Vite dev server proxies `/api` → `http://localhost:8000` |
|
||||||
|
| Preview (`npm run preview`) | Same proxy (used by the Playwright webServer) |
|
||||||
|
| Docker (compose) | Nginx `location /api/` proxies to the `backend:8000` service |
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
### Unit tests (Vitest + React Testing Library)
|
||||||
|
|
||||||
|
Located in `src/tests/`. Run with `npm test`.
|
||||||
|
|
||||||
|
- `Header.test.tsx` — brand, router links, lucide icons, active state, mobile menu
|
||||||
|
- `ArticleCard.test.tsx` — data rendering, links, fallbacks, read time
|
||||||
|
- `Layout.test.tsx` — shell structure, API status indicator (mocked `getHealth`)
|
||||||
|
- `components/` — `CategoryBadge` variants, `AuthorAvatar` initials/image
|
||||||
|
|
||||||
|
Components that use the router are rendered through the `renderWithRouter`
|
||||||
|
helper (`src/tests/utils.tsx`), which wraps them in a `MemoryRouter`.
|
||||||
|
|
||||||
|
### E2E tests (Playwright)
|
||||||
|
|
||||||
|
Located in `playwright/e2e/`. Run with `npm run e2e` (builds the app first and
|
||||||
|
serves it via `vite preview` on port 4173).
|
||||||
|
|
||||||
|
- `home.spec.ts` — page shell, feed rendering with data, client-side
|
||||||
|
navigation between pages (asserts no full page reloads), article detail
|
||||||
|
route, console/page-error hygiene
|
||||||
|
- `api.spec.ts` — health request on load, rendering API-provided articles,
|
||||||
|
sample-data fallback when the API is down, 404 error-envelope handling.
|
||||||
|
Endpoints are mocked with `page.route`, so the tests are deterministic
|
||||||
|
without a running backend.
|
||||||
|
|
||||||
|
Install browsers after a fresh clone:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx playwright install chromium
|
||||||
|
```
|
||||||
|
|
||||||
|
## Docker
|
||||||
|
|
||||||
|
Multi-stage [`Dockerfile`](Dockerfile): `node:20-alpine` builds the production
|
||||||
|
bundle; `nginx:1.27-alpine` serves it with SPA fallback and an `/api/` proxy
|
||||||
|
to the `backend` service (see [`nginx.conf`](nginx.conf)).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# From this directory (standalone: frontend + backend)
|
||||||
|
docker compose up --build
|
||||||
|
|
||||||
|
# Or from the repository root (full orchestration)
|
||||||
|
docker compose up --build
|
||||||
|
```
|
||||||
|
|
||||||
|
The app is served on <http://localhost:3000>.
|
||||||
|
|
||||||
|
## Environment variables
|
||||||
|
|
||||||
|
| Variable | Default | Description |
|
||||||
|
| --------------------- | --------- | ------------------------------------ |
|
||||||
|
| `VITE_API_BASE_URL` | `/api/v1` | API base URL baked in at build time |
|
||||||
|
|
||||||
|
No secrets are required on the client side; authentication and credentials
|
||||||
|
are handled by the backend in future milestones.
|
||||||
|
|
||||||
|
## Icons (lucide-react)
|
||||||
|
|
||||||
|
Icons are imported from `lucide-react` (SVG-based, no font downloads) and are
|
||||||
|
always decorative — paired with a text label or `aria-label`, and marked
|
||||||
|
`aria-hidden="true"`:
|
||||||
|
|
||||||
|
| Icon | Where used |
|
||||||
|
| ----------------- | ------------------------------------------------- |
|
||||||
|
| `Home` | Header — "Home" nav item |
|
||||||
|
| `FileText` | Header — "Articles" nav item; article thumbnail |
|
||||||
|
| `Settings` | Header — "Categories" nav item |
|
||||||
|
| `Search` | Home — search bar |
|
||||||
|
| `Menu` / `X` | Header — mobile menu toggle |
|
||||||
|
| `Clock` | ArticleCard / hero — read time |
|
||||||
|
| `ArrowRight` | Hero — "Read article" call to action |
|
||||||
|
| `ArrowLeft` | ArticlePage — back links |
|
||||||
|
| `Info` | Home — sample-data notice |
|
||||||
|
| `FolderOpen` | CategoriesPage — category cards |
|
||||||
|
|
||||||
|
Browse all available icons at <https://lucide.dev/icons>.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
- **Port 5173 already in use** — Vite picks the next free port; use
|
||||||
|
`npm run dev -- --strictPort` to fail instead.
|
||||||
|
- **E2E fails with "browser not found"** — run `npx playwright install
|
||||||
|
chromium` (add `--with-deps` on distros where you have root/sudo access).
|
||||||
|
- **"API: offline" in the footer** — the backend is not running on
|
||||||
|
`http://localhost:8000`; expected when only the frontend is up.
|
||||||
|
- **Sample data notice on the home page** — the backend does not implement
|
||||||
|
`GET /api/v1/articles` yet (planned milestone); the fallback is intentional.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Standalone frontend service (the full application orchestration lives in
|
||||||
|
# the repository root `docker-compose.yml`).
|
||||||
|
#
|
||||||
|
# docker compose up --build
|
||||||
|
#
|
||||||
|
# Frontend: http://localhost:3000 (Nginx proxies /api to the backend).
|
||||||
|
# Backend: http://localhost:8000 (Swagger docs at /api/v1/docs).
|
||||||
|
services:
|
||||||
|
frontend:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "3000:80"
|
||||||
|
depends_on:
|
||||||
|
backend:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
# Included so this compose file works on its own (mirrors the root file).
|
||||||
|
backend:
|
||||||
|
build: ../backend
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
volumes:
|
||||||
|
- ../data/db:/app/data/db
|
||||||
|
environment:
|
||||||
|
- DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
restart: unless-stopped
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="newzy — a news web application for discovering, reading, and managing news content."
|
||||||
|
/>
|
||||||
|
<title>newzy — Your news, curated</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# newzy frontend — Nginx configuration (Docker).
|
||||||
|
#
|
||||||
|
# Serves the Vite production build as a single-page app and proxies API
|
||||||
|
# calls to the backend service so the browser can use relative /api URLs
|
||||||
|
# (no CORS needed from within the compose network).
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
# Reasonable defaults for static content.
|
||||||
|
sendfile on;
|
||||||
|
gzip on;
|
||||||
|
gzip_types text/css application/javascript application/json image/svg+xml;
|
||||||
|
|
||||||
|
# Hashed build assets can be cached aggressively.
|
||||||
|
location /assets/ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Docker's built-in DNS. The upstream is resolved at request time (via a
|
||||||
|
# variable) instead of at startup, so nginx still boots when the backend
|
||||||
|
# service is not yet available (requests then fail with 502 instead).
|
||||||
|
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||||
|
|
||||||
|
# Proxy API calls to the FastAPI backend service.
|
||||||
|
location /api/ {
|
||||||
|
set $api_upstream "http://backend:8000";
|
||||||
|
proxy_pass $api_upstream;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# SPA fallback: unknown paths are handled by React Router.
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+7596
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
|||||||
|
{
|
||||||
|
"name": "newzy-frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"description": "Frontend for the newzy news web application — React + TypeScript + Vite.",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc && vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest",
|
||||||
|
"test:coverage": "vitest run --coverage",
|
||||||
|
"e2e": "playwright test",
|
||||||
|
"e2e:ui": "playwright test --ui",
|
||||||
|
"lint": "eslint . --ext .js,.jsx,.ts,.tsx"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"class-variance-authority": "^0.7.0",
|
||||||
|
"clsx": "^2.1.0",
|
||||||
|
"lucide-react": "^0.263.0",
|
||||||
|
"react": "^18.2.0",
|
||||||
|
"react-dom": "^18.2.0",
|
||||||
|
"react-router-dom": "^6.20.0",
|
||||||
|
"tailwind-merge": "^2.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.39.0",
|
||||||
|
"@testing-library/dom": "^9.3.4",
|
||||||
|
"@testing-library/jest-dom": "^6.4.2",
|
||||||
|
"@testing-library/react": "^14.2.0",
|
||||||
|
"@types/react": "^18.2.0",
|
||||||
|
"@types/react-dom": "^18.2.0",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
||||||
|
"@typescript-eslint/parser": "^6.21.0",
|
||||||
|
"@vitejs/plugin-react": "^4.2.0",
|
||||||
|
"@vitest/coverage-v8": "^0.34.0",
|
||||||
|
"autoprefixer": "^10.4.16",
|
||||||
|
"eslint": "^8.57.0",
|
||||||
|
"eslint-plugin-react": "^7.34.0",
|
||||||
|
"eslint-plugin-react-hooks": "^4.6.0",
|
||||||
|
"jsdom": "^24.0.0",
|
||||||
|
"postcss": "^8.4.32",
|
||||||
|
"tailwindcss": "^3.4.0",
|
||||||
|
"typescript": "~5.4.2",
|
||||||
|
"vite": "^4.4.0",
|
||||||
|
"vitest": "^0.34.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { defineConfig, devices } from '@playwright/test';
|
||||||
|
|
||||||
|
// https://playwright.dev/docs/test-configuration
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: './playwright/e2e',
|
||||||
|
fullyParallel: true,
|
||||||
|
forbidOnly: !!process.env.CI,
|
||||||
|
retries: process.env.CI ? 2 : 0,
|
||||||
|
workers: process.env.CI ? 1 : undefined,
|
||||||
|
reporter: process.env.CI ? 'github' : 'list',
|
||||||
|
timeout: 30_000,
|
||||||
|
use: {
|
||||||
|
baseURL: 'http://localhost:4173',
|
||||||
|
trace: 'on-first-retry',
|
||||||
|
screenshot: 'only-on-failure',
|
||||||
|
},
|
||||||
|
projects: [
|
||||||
|
{
|
||||||
|
name: 'chromium',
|
||||||
|
use: { ...devices['Desktop Chrome'] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
webServer: {
|
||||||
|
// Serve the production build (vite preview) with the /api proxy enabled.
|
||||||
|
command: 'npm run build && npm run preview -- --strictPort',
|
||||||
|
url: 'http://localhost:4173',
|
||||||
|
reuseExistingServer: !process.env.CI,
|
||||||
|
timeout: 120_000,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import { expect, test, type Page } from '@playwright/test';
|
||||||
|
|
||||||
|
const HEALTH_OK = { status: 'ok', version: '0.1.0' };
|
||||||
|
|
||||||
|
const API_ARTICLE = {
|
||||||
|
id: 100,
|
||||||
|
title: 'Live API Article',
|
||||||
|
content: 'This story was served by the (mocked) newzy backend API. '.repeat(20),
|
||||||
|
author_id: 7,
|
||||||
|
category_id: 1,
|
||||||
|
created_at: '2025-06-01T08:00:00Z',
|
||||||
|
published: true,
|
||||||
|
author: {
|
||||||
|
id: 7,
|
||||||
|
name: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com',
|
||||||
|
bio: null,
|
||||||
|
},
|
||||||
|
category: { id: 1, name: 'Technology', slug: 'technology' },
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Mock the health endpoint so tests do not depend on a running backend. */
|
||||||
|
async function mockHealth(page: Page): Promise<void> {
|
||||||
|
await page.route('**/api/v1/health', (route) =>
|
||||||
|
route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify(HEALTH_OK),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API interactions: verifies the app talks to the backend through the
|
||||||
|
* typed client (base URL /api/v1, JSON accept header) and reflects the
|
||||||
|
* responses in the UI.
|
||||||
|
*/
|
||||||
|
test.describe('api interactions', () => {
|
||||||
|
test('requests the backend health endpoint on load and reports it online', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await mockHealth(page);
|
||||||
|
|
||||||
|
const healthRequest = page.waitForRequest(
|
||||||
|
(request) => request.url().includes('/api/v1/health') && request.method() === 'GET',
|
||||||
|
);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
const request = await healthRequest;
|
||||||
|
expect(request.headers()['accept']).toBe('application/json');
|
||||||
|
|
||||||
|
await expect(page.getByTestId('api-status')).toHaveText(/api:\s*online/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renders articles returned by the API', async ({ page }) => {
|
||||||
|
await mockHealth(page);
|
||||||
|
await page.route('**/api/v1/articles', (route) =>
|
||||||
|
route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify([API_ARTICLE]),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
|
||||||
|
// The API article replaces the sample feed.
|
||||||
|
const cards = page.getByTestId('article-card');
|
||||||
|
await expect(cards).toHaveCount(1);
|
||||||
|
await expect(cards.first()).toContainText('Live API Article');
|
||||||
|
await expect(cards.first()).toContainText('Ada Lovelace');
|
||||||
|
await expect(cards.first()).toContainText('Technology');
|
||||||
|
|
||||||
|
// Sample-data fallback note is hidden when real data is present.
|
||||||
|
await expect(page.getByTestId('sample-data-note')).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('falls back to sample data and reports the API as offline', async ({ page }) => {
|
||||||
|
// Block every API call to simulate the backend being down.
|
||||||
|
await page.route('**/api/v1/**', (route) => route.abort());
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
|
||||||
|
await expect(page.getByTestId('sample-data-note')).toBeVisible();
|
||||||
|
await expect(page.getByTestId('article-card').first()).toBeVisible();
|
||||||
|
await expect(page.getByTestId('api-status')).toHaveText(/api:\s*offline/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('survives API error responses (non-2xx envelope)', async ({ page }) => {
|
||||||
|
await mockHealth(page);
|
||||||
|
await page.route('**/api/v1/articles', (route) =>
|
||||||
|
route.fulfill({
|
||||||
|
status: 404,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ detail: 'Not Found', code: 'not_found' }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const pageErrors: string[] = [];
|
||||||
|
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
|
||||||
|
// 404 from the articles endpoint -> graceful sample-data fallback.
|
||||||
|
await expect(page.getByTestId('sample-data-note')).toBeVisible();
|
||||||
|
await expect(page.getByTestId('article-card').first()).toBeVisible();
|
||||||
|
expect(pageErrors).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Homepage flows: page shell, article feed, and client-side navigation
|
||||||
|
* between pages via React Router links (no full page reloads).
|
||||||
|
*/
|
||||||
|
test.describe('home page', () => {
|
||||||
|
test('renders the page shell, branding and navigation', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await expect(page).toHaveTitle(/newzy/i);
|
||||||
|
|
||||||
|
// Layout structure: header, main content, footer.
|
||||||
|
await expect(page.getByRole('banner')).toBeVisible();
|
||||||
|
await expect(page.getByRole('main')).toBeVisible();
|
||||||
|
await expect(page.getByRole('contentinfo')).toBeVisible();
|
||||||
|
|
||||||
|
// Brand links to home.
|
||||||
|
await expect(page.getByRole('link', { name: 'newzy' })).toHaveAttribute('href', '/');
|
||||||
|
|
||||||
|
// Primary navigation uses React Router links.
|
||||||
|
const nav = page.getByRole('navigation', { name: 'Main navigation' });
|
||||||
|
await expect(nav.getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
|
||||||
|
await expect(nav.getByRole('link', { name: /articles/i })).toHaveAttribute(
|
||||||
|
'href',
|
||||||
|
'/articles',
|
||||||
|
);
|
||||||
|
await expect(nav.getByRole('link', { name: /categories/i })).toHaveAttribute(
|
||||||
|
'href',
|
||||||
|
'/categories',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renders the featured article and article grid with data', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
|
||||||
|
// Hero with the featured article.
|
||||||
|
const featured = page.getByRole('region', { name: 'Featured article' });
|
||||||
|
await expect(featured).toBeVisible();
|
||||||
|
await expect(featured.getByRole('heading', { level: 1 })).toContainText(
|
||||||
|
'Inside the new wave of open-source language models',
|
||||||
|
);
|
||||||
|
|
||||||
|
// Article grid rendered from data (sample feed while the backend article
|
||||||
|
// endpoints are not available yet).
|
||||||
|
const cards = page.getByTestId('article-card');
|
||||||
|
await expect(cards.first()).toBeVisible();
|
||||||
|
expect(await cards.count()).toBeGreaterThanOrEqual(5);
|
||||||
|
await expect(page.getByTestId('sample-data-note')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('navigates between pages via router links without a full page reload', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const loadEvents: string[] = [];
|
||||||
|
page.on('load', () => loadEvents.push(page.url()));
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
const nav = page.getByRole('navigation', { name: 'Main navigation' });
|
||||||
|
|
||||||
|
// Home -> Articles
|
||||||
|
await nav.getByRole('link', { name: /articles/i }).click();
|
||||||
|
await expect(page).toHaveURL(/\/articles$/);
|
||||||
|
await expect(
|
||||||
|
page.getByRole('heading', { level: 1, name: 'Articles' }),
|
||||||
|
).toBeVisible();
|
||||||
|
|
||||||
|
// Articles -> Categories
|
||||||
|
await nav.getByRole('link', { name: /categories/i }).click();
|
||||||
|
await expect(page).toHaveURL(/\/categories$/);
|
||||||
|
await expect(
|
||||||
|
page.getByRole('heading', { level: 1, name: 'Categories' }),
|
||||||
|
).toBeVisible();
|
||||||
|
|
||||||
|
// Categories -> Home
|
||||||
|
await nav.getByRole('link', { name: /home/i }).click();
|
||||||
|
await expect(page).toHaveURL(/\/$/);
|
||||||
|
|
||||||
|
// Only the initial goto fired a document load — the rest was
|
||||||
|
// client-side React Router navigation.
|
||||||
|
expect(loadEvents).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('opens an article detail placeholder from a card', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
|
||||||
|
const firstCard = page.getByTestId('article-card').first();
|
||||||
|
await firstCard.getByRole('link').first().click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(/\/articles\/\d+$/);
|
||||||
|
await expect(page.getByRole('heading', { level: 1 })).toContainText('Article #');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('has no unexpected console errors or uncaught page errors', async ({ page }) => {
|
||||||
|
const consoleErrors: string[] = [];
|
||||||
|
const pageErrors: string[] = [];
|
||||||
|
page.on('console', (message) => {
|
||||||
|
if (message.type() === 'error') consoleErrors.push(message.text());
|
||||||
|
});
|
||||||
|
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
await expect(page.getByTestId('article-card').first()).toBeVisible();
|
||||||
|
|
||||||
|
// Uncaught exceptions are never acceptable.
|
||||||
|
expect(pageErrors).toEqual([]);
|
||||||
|
|
||||||
|
// Expected noise: the article feed fetch 404s/502s when the backend
|
||||||
|
// article endpoints are unavailable (the UI falls back to sample data).
|
||||||
|
const unexpected = consoleErrors.filter(
|
||||||
|
(text) => !/failed to load resource|net::err/i.test(text),
|
||||||
|
);
|
||||||
|
expect(unexpected).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none" role="img" aria-label="newzy logo">
|
||||||
|
<rect width="32" height="32" rx="7" fill="#2563eb"/>
|
||||||
|
<rect x="7" y="8" width="18" height="4" rx="1.2" fill="#ffffff"/>
|
||||||
|
<rect x="7" y="15" width="8" height="9" rx="1.2" fill="#bfdbfe"/>
|
||||||
|
<rect x="17.5" y="15" width="7.5" height="2" rx="1" fill="#ffffff"/>
|
||||||
|
<rect x="17.5" y="19" width="7.5" height="2" rx="1" fill="#ffffff"/>
|
||||||
|
<rect x="17.5" y="23" width="5" height="2" rx="1" fill="#ffffff"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 517 B |
@@ -0,0 +1,2 @@
|
|||||||
|
User-agent: *
|
||||||
|
Allow: /
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';
|
||||||
|
import Layout from './components/ui/Layout';
|
||||||
|
import ArticlePage from './pages/ArticlePage';
|
||||||
|
import CategoriesPage from './pages/CategoriesPage';
|
||||||
|
import Home from './pages/Home';
|
||||||
|
|
||||||
|
/** 404 fallback for unknown routes. */
|
||||||
|
function NotFound() {
|
||||||
|
return (
|
||||||
|
<div className="container-page text-center">
|
||||||
|
<h1 className="mb-2 text-5xl font-bold text-slate-900">404</h1>
|
||||||
|
<p className="mb-6 text-sm text-slate-600">
|
||||||
|
That page could not be found. It may have moved, or the link may be broken.
|
||||||
|
</p>
|
||||||
|
<Link to="/" className="btn">
|
||||||
|
Back to home
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Root component: owns the React Router setup.
|
||||||
|
*
|
||||||
|
* BrowserRouter wraps the whole app; Layout provides the shared shell
|
||||||
|
* (header/footer); Routes maps URLs to page components in src/pages/.
|
||||||
|
* In-app navigation always uses react-router-dom <Link>/<NavLink>.
|
||||||
|
*/
|
||||||
|
export default function App() {
|
||||||
|
return (
|
||||||
|
<BrowserRouter
|
||||||
|
future={{
|
||||||
|
v7_startTransition: true,
|
||||||
|
v7_relativeSplatPath: true,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Layout>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/" element={<Home />} />
|
||||||
|
<Route path="/articles" element={<ArticlePage />} />
|
||||||
|
<Route path="/articles/:id" element={<ArticlePage />} />
|
||||||
|
<Route path="/categories" element={<CategoriesPage />} />
|
||||||
|
<Route path="*" element={<NotFound />} />
|
||||||
|
</Routes>
|
||||||
|
</Layout>
|
||||||
|
</BrowserRouter>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none" role="img" aria-label="newzy logo">
|
||||||
|
<rect width="32" height="32" rx="7" fill="#2563eb"/>
|
||||||
|
<rect x="7" y="8" width="18" height="4" rx="1.2" fill="#ffffff"/>
|
||||||
|
<rect x="7" y="15" width="8" height="9" rx="1.2" fill="#bfdbfe"/>
|
||||||
|
<rect x="17.5" y="15" width="7.5" height="2" rx="1" fill="#ffffff"/>
|
||||||
|
<rect x="17.5" y="19" width="7.5" height="2" rx="1" fill="#ffffff"/>
|
||||||
|
<rect x="17.5" y="23" width="5" height="2" rx="1" fill="#ffffff"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 517 B |
@@ -0,0 +1,34 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
:root {
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
@apply scroll-smooth;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
@apply bg-slate-50 text-slate-900 antialiased;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer components {
|
||||||
|
/* Centered page container used by all pages. */
|
||||||
|
.container-page {
|
||||||
|
@apply mx-auto w-full max-w-6xl px-4 py-8 sm:px-6;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Primary button style (links and buttons). */
|
||||||
|
.btn {
|
||||||
|
@apply inline-flex items-center justify-center gap-2 rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Secondary button style. */
|
||||||
|
.btn-secondary {
|
||||||
|
@apply inline-flex items-center justify-center gap-2 rounded-md border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { Clock, FileText } from 'lucide-react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import type { Article } from '../../types';
|
||||||
|
import { cn } from '../../lib/utils';
|
||||||
|
import { AuthorAvatar } from './AuthorAvatar';
|
||||||
|
import { CategoryBadge } from './CategoryBadge';
|
||||||
|
|
||||||
|
const WORDS_PER_MINUTE = 200;
|
||||||
|
|
||||||
|
/** Estimate reading time in minutes (minimum 1). */
|
||||||
|
export function getReadTime(content: string): number {
|
||||||
|
const words = content.trim().split(/\s+/).filter(Boolean).length;
|
||||||
|
return Math.max(1, Math.round(words / WORDS_PER_MINUTE));
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatPublished(value: Article['createdAt']): string {
|
||||||
|
const date = value instanceof Date ? value : new Date(value);
|
||||||
|
if (Number.isNaN(date.getTime())) return '';
|
||||||
|
return date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ArticleCardProps {
|
||||||
|
article: Article;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reusable article preview: thumbnail placeholder, category badge, title,
|
||||||
|
* excerpt, author (via AuthorAvatar) and estimated read time. Links to the
|
||||||
|
* article detail route via react-router-dom.
|
||||||
|
*/
|
||||||
|
export function ArticleCard({ article, className }: ArticleCardProps) {
|
||||||
|
const author =
|
||||||
|
article.author ?? { id: article.authorId, name: 'Unknown author', email: '' };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<article
|
||||||
|
data-testid="article-card"
|
||||||
|
className={cn(
|
||||||
|
'group flex flex-col overflow-hidden rounded-lg border border-slate-200 bg-white shadow-sm transition-shadow hover:shadow-md',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{/* Thumbnail placeholder (images arrive with a later milestone) */}
|
||||||
|
<Link
|
||||||
|
to={`/articles/${article.id}`}
|
||||||
|
aria-label={`Read article: ${article.title}`}
|
||||||
|
className="flex h-36 items-center justify-center bg-slate-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-blue-500"
|
||||||
|
>
|
||||||
|
<FileText className="h-10 w-10 text-slate-400" aria-hidden="true" />
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<div className="flex flex-1 flex-col gap-2 p-4">
|
||||||
|
{article.category && <CategoryBadge category={article.category} />}
|
||||||
|
|
||||||
|
<h3 className="text-base font-semibold leading-snug text-slate-900">
|
||||||
|
<Link
|
||||||
|
to={`/articles/${article.id}`}
|
||||||
|
className="hover:text-blue-700 hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||||
|
>
|
||||||
|
{article.title}
|
||||||
|
</Link>
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<p className="line-clamp-3 text-sm text-slate-600">{article.content}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between gap-2 border-t border-slate-100 px-4 py-3">
|
||||||
|
<span className="flex min-w-0 items-center gap-2 text-sm text-slate-600">
|
||||||
|
<AuthorAvatar author={author} size="sm" />
|
||||||
|
<span className="truncate">{author.name}</span>
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="flex shrink-0 items-center gap-1 text-xs text-slate-500"
|
||||||
|
title={formatPublished(article.createdAt)}
|
||||||
|
>
|
||||||
|
<Clock className="h-3.5 w-3.5" aria-hidden="true" />
|
||||||
|
{getReadTime(article.content)} min read
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ArticleCard;
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import type { Author } from '../../types';
|
||||||
|
import { cn } from '../../lib/utils';
|
||||||
|
|
||||||
|
export interface AuthorAvatarProps {
|
||||||
|
author: Pick<Author, 'name' | 'avatar'>;
|
||||||
|
size?: 'sm' | 'md' | 'lg';
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SIZE_CLASSES = {
|
||||||
|
sm: 'h-6 w-6 text-[0.65rem]',
|
||||||
|
md: 'h-9 w-9 text-sm',
|
||||||
|
lg: 'h-12 w-12 text-base',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/** Derive up to two initials from a full name ("Ada Lovelace" -> "AL"). */
|
||||||
|
export function initialsOf(name: string): string {
|
||||||
|
return name
|
||||||
|
.split(/\s+/)
|
||||||
|
.filter(Boolean)
|
||||||
|
.slice(0, 2)
|
||||||
|
.map((part) => part.charAt(0).toUpperCase())
|
||||||
|
.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Author profile indicator: shows the profile image when available,
|
||||||
|
* otherwise the author's initials. The author's name is exposed as a hover
|
||||||
|
* tooltip (`title`) and as the accessible label.
|
||||||
|
*/
|
||||||
|
export function AuthorAvatar({ author, size = 'md', className }: AuthorAvatarProps) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-testid="author-avatar"
|
||||||
|
title={author.name}
|
||||||
|
aria-label={author.name}
|
||||||
|
className={cn(
|
||||||
|
'inline-flex shrink-0 items-center justify-center rounded-full bg-slate-200 font-semibold text-slate-700',
|
||||||
|
SIZE_CLASSES[size],
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{author.avatar ? (
|
||||||
|
<img
|
||||||
|
src={author.avatar}
|
||||||
|
alt={author.name}
|
||||||
|
className="h-full w-full rounded-full object-cover"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
initialsOf(author.name)
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AuthorAvatar;
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { cva, type VariantProps } from 'class-variance-authority';
|
||||||
|
import type { Category } from '../../types';
|
||||||
|
import { cn } from '../../lib/utils';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Color-coded category pill.
|
||||||
|
*
|
||||||
|
* The tone is derived from the category slug (stable, URL-safe identifier);
|
||||||
|
* unknown slugs fall back to a neutral slate tone.
|
||||||
|
*/
|
||||||
|
const badgeVariants = cva(
|
||||||
|
'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
tone: {
|
||||||
|
blue: 'bg-blue-100 text-blue-800',
|
||||||
|
green: 'bg-green-100 text-green-800',
|
||||||
|
amber: 'bg-amber-100 text-amber-800',
|
||||||
|
purple: 'bg-purple-100 text-purple-800',
|
||||||
|
rose: 'bg-rose-100 text-rose-800',
|
||||||
|
slate: 'bg-slate-100 text-slate-700',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
tone: 'slate',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
type BadgeTone = NonNullable<VariantProps<typeof badgeVariants>['tone']>;
|
||||||
|
|
||||||
|
const TONE_BY_SLUG: Record<string, BadgeTone> = {
|
||||||
|
technology: 'blue',
|
||||||
|
science: 'green',
|
||||||
|
sports: 'amber',
|
||||||
|
culture: 'purple',
|
||||||
|
world: 'rose',
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface CategoryBadgeProps {
|
||||||
|
category: Pick<Category, 'name' | 'slug'>;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CategoryBadge({ category, className }: CategoryBadgeProps) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-testid="category-badge"
|
||||||
|
className={cn(badgeVariants({ tone: TONE_BY_SLUG[category.slug] }), className)}
|
||||||
|
>
|
||||||
|
{category.name}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CategoryBadge;
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { FileText, Home, Menu, Settings, X, type LucideIcon } from 'lucide-react';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { NavLink } from 'react-router-dom';
|
||||||
|
import logo from '../../assets/logo.svg';
|
||||||
|
import { cn } from '../../lib/utils';
|
||||||
|
|
||||||
|
export interface HeaderProps {
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NavItem {
|
||||||
|
to: string;
|
||||||
|
label: string;
|
||||||
|
icon: LucideIcon;
|
||||||
|
/** Match the route exactly (used for "/"). */
|
||||||
|
end?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const NAV_ITEMS: NavItem[] = [
|
||||||
|
{ to: '/', label: 'Home', icon: Home, end: true },
|
||||||
|
{ to: '/articles', label: 'Articles', icon: FileText },
|
||||||
|
{ to: '/categories', label: 'Categories', icon: Settings },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main navigation header.
|
||||||
|
*
|
||||||
|
* Uses react-router-dom <NavLink> (never plain anchors) so navigation stays
|
||||||
|
* client-side. Lucide icons mark each item; the mobile menu collapses the
|
||||||
|
* same links into a toggleable panel below <md> breakpoints.
|
||||||
|
*/
|
||||||
|
export function Header({ className }: HeaderProps) {
|
||||||
|
const [menuOpen, setMenuOpen] = useState(false);
|
||||||
|
|
||||||
|
const closeMenu = () => setMenuOpen(false);
|
||||||
|
|
||||||
|
const linkClasses = ({ isActive }: { isActive: boolean }): string =>
|
||||||
|
cn(
|
||||||
|
'inline-flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors',
|
||||||
|
'text-slate-600 hover:bg-slate-100 hover:text-slate-900',
|
||||||
|
isActive && 'bg-blue-50 text-blue-700 hover:bg-blue-100 hover:text-blue-800',
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderNav = (id: string, itemClasses?: string) => (
|
||||||
|
<nav id={id} aria-label={`${id === 'mobile-menu' ? 'Mobile' : 'Main'} navigation`} className={itemClasses}>
|
||||||
|
{NAV_ITEMS.map(({ to, label, icon: Icon, end }) => (
|
||||||
|
<NavLink
|
||||||
|
key={to}
|
||||||
|
to={to}
|
||||||
|
end={end}
|
||||||
|
className={({ isActive }) => linkClasses({ isActive })}
|
||||||
|
onClick={closeMenu}
|
||||||
|
>
|
||||||
|
<Icon className="h-5 w-5" aria-hidden="true" />
|
||||||
|
<span>{label}</span>
|
||||||
|
</NavLink>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<header
|
||||||
|
data-testid="site-header"
|
||||||
|
className={cn('sticky top-0 z-40 border-b border-slate-200 bg-white/95 backdrop-blur', className)}
|
||||||
|
>
|
||||||
|
<div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-3 sm:px-6">
|
||||||
|
{/* Brand */}
|
||||||
|
<NavLink to="/" className="flex items-center gap-2" onClick={closeMenu} aria-label="newzy">
|
||||||
|
<img src={logo} alt="" className="h-8 w-8" />
|
||||||
|
<span className="text-xl font-bold tracking-tight text-slate-900">newzy</span>
|
||||||
|
</NavLink>
|
||||||
|
|
||||||
|
{/* Desktop navigation */}
|
||||||
|
{renderNav('main-nav', 'hidden items-center gap-1 md:flex')}
|
||||||
|
|
||||||
|
{/* Mobile menu toggle */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="inline-flex items-center justify-center rounded-md p-2 text-slate-600 hover:bg-slate-100 hover:text-slate-900 md:hidden"
|
||||||
|
aria-label={menuOpen ? 'Close menu' : 'Open menu'}
|
||||||
|
aria-expanded={menuOpen}
|
||||||
|
aria-controls="mobile-menu"
|
||||||
|
onClick={() => setMenuOpen((open) => !open)}
|
||||||
|
>
|
||||||
|
{menuOpen ? (
|
||||||
|
<X className="h-6 w-6" aria-hidden="true" />
|
||||||
|
) : (
|
||||||
|
<Menu className="h-6 w-6" aria-hidden="true" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Mobile navigation (rendered only while open) */}
|
||||||
|
{menuOpen && renderNav('mobile-menu', 'flex flex-col gap-1 border-t border-slate-200 px-4 pb-4 pt-2 md:hidden')}
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Header;
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { getHealth } from '../../api/client';
|
||||||
|
import { cn } from '../../lib/utils';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Header } from './Header';
|
||||||
|
|
||||||
|
export interface LayoutProps {
|
||||||
|
children: ReactNode;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type ApiStatus = 'checking' | 'online' | 'offline';
|
||||||
|
|
||||||
|
const STATUS_STYLES: Record<ApiStatus, string> = {
|
||||||
|
checking: 'bg-amber-400',
|
||||||
|
online: 'bg-green-500',
|
||||||
|
offline: 'bg-red-500',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Application shell: sticky header, routed page content, and a footer with a
|
||||||
|
* backend API status indicator (fetched from `GET /api/v1/health` on mount).
|
||||||
|
*/
|
||||||
|
export function Layout({ children, className }: LayoutProps) {
|
||||||
|
const [apiStatus, setApiStatus] = useState<ApiStatus>('checking');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
getHealth()
|
||||||
|
.then(() => {
|
||||||
|
if (active) setApiStatus('online');
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (active) setApiStatus('offline');
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('flex min-h-screen flex-col', className)}>
|
||||||
|
<Header />
|
||||||
|
|
||||||
|
<main id="main-content" className="flex-1">
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer className="border-t border-slate-200 bg-white">
|
||||||
|
<div className="mx-auto flex max-w-6xl flex-col items-center justify-between gap-2 px-4 py-6 text-sm text-slate-500 sm:flex-row sm:px-6">
|
||||||
|
<p>
|
||||||
|
© {new Date().getFullYear()} newzy — your news, curated.
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
data-testid="api-status"
|
||||||
|
aria-live="polite"
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
title="newzy backend API status"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className={cn('h-2.5 w-2.5 rounded-full', STATUS_STYLES[apiStatus])}
|
||||||
|
/>
|
||||||
|
API: {apiStatus}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Layout;
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { clsx, type ClassValue } from 'clsx';
|
||||||
|
import { twMerge } from 'tailwind-merge';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge Tailwind CSS classes with conflict resolution.
|
||||||
|
*
|
||||||
|
* Combines `clsx` (conditional class names) with `tailwind-merge` (drops
|
||||||
|
* conflicting utilities, last one wins) so component classes can be safely
|
||||||
|
* extended from props: `cn(baseClasses, props.className)`.
|
||||||
|
*/
|
||||||
|
export function cn(...inputs: ClassValue[]): string {
|
||||||
|
return twMerge(clsx(inputs));
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import ReactDOM from 'react-dom/client';
|
||||||
|
import App from './App';
|
||||||
|
import './assets/styles/globals.css';
|
||||||
|
|
||||||
|
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<App />
|
||||||
|
</React.StrictMode>,
|
||||||
|
);
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { ArrowLeft, FileText } from 'lucide-react';
|
||||||
|
import { Link, useParams } from 'react-router-dom';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Article view placeholder.
|
||||||
|
*
|
||||||
|
* - `/articles` — "all articles" layout (listing arrives in a later milestone)
|
||||||
|
* - `/articles/:id` — single article layout (reads the id via useParams)
|
||||||
|
*/
|
||||||
|
export function ArticlePage() {
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
|
||||||
|
if (id) {
|
||||||
|
return (
|
||||||
|
<div className="container-page">
|
||||||
|
<nav aria-label="Breadcrumb" className="mb-6">
|
||||||
|
<Link
|
||||||
|
to="/articles"
|
||||||
|
className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700 hover:underline"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" aria-hidden="true" />
|
||||||
|
All articles
|
||||||
|
</Link>
|
||||||
|
</nav>
|
||||||
|
<Placeholder
|
||||||
|
heading={`Article #${id}`}
|
||||||
|
description="The full article view lands in a later milestone. This placeholder proves that the /articles/:id route works end to end."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="container-page">
|
||||||
|
<Placeholder
|
||||||
|
heading="Articles"
|
||||||
|
description="Every published story from newzy, in one place. The complete listing is coming in a later milestone — meanwhile, browse the latest on the home page."
|
||||||
|
action={
|
||||||
|
<Link to="/" className="btn">
|
||||||
|
<ArrowLeft className="h-4 w-4" aria-hidden="true" />
|
||||||
|
Back to home
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PlaceholderProps {
|
||||||
|
heading: string;
|
||||||
|
description: string;
|
||||||
|
action?: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Placeholder({ heading, description, action }: PlaceholderProps) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1 className="mb-6 text-3xl font-bold text-slate-900">{heading}</h1>
|
||||||
|
<div className="flex flex-col items-start gap-4 rounded-xl border border-dashed border-slate-300 bg-white p-8">
|
||||||
|
<FileText className="h-10 w-10 text-slate-300" aria-hidden="true" />
|
||||||
|
<p className="max-w-prose text-sm leading-relaxed text-slate-600">{description}</p>
|
||||||
|
{action}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ArticlePage;
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { FolderOpen } from 'lucide-react';
|
||||||
|
import { CategoryBadge } from '../components/articles/CategoryBadge';
|
||||||
|
import { sampleArticles, sampleCategories } from '../data/sample';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Categories listing page (placeholder layout).
|
||||||
|
*
|
||||||
|
* Renders the known categories with article counts derived from the sample
|
||||||
|
* feed; the real listing will be fetched from the backend in a later
|
||||||
|
* milestone.
|
||||||
|
*/
|
||||||
|
export function CategoriesPage() {
|
||||||
|
const counts = sampleCategories.map((category) => ({
|
||||||
|
category,
|
||||||
|
articleCount: sampleArticles.filter((article) => article.categoryId === category.id).length,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="container-page">
|
||||||
|
<h1 className="mb-2 text-3xl font-bold text-slate-900">Categories</h1>
|
||||||
|
<p className="mb-8 max-w-prose text-sm text-slate-600">
|
||||||
|
Browse newzy by topic. This layout is a placeholder — category pages
|
||||||
|
with full article listings arrive in a later milestone.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
{counts.map(({ category, articleCount }) => (
|
||||||
|
<div
|
||||||
|
key={category.id}
|
||||||
|
className="flex items-center justify-between gap-4 rounded-lg border border-slate-200 bg-white p-5 shadow-sm"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<FolderOpen className="h-6 w-6 text-slate-400" aria-hidden="true" />
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-slate-900">{category.name}</p>
|
||||||
|
<p className="text-xs text-slate-500">/{category.slug}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<CategoryBadge category={category} />
|
||||||
|
<span className="text-sm text-slate-500">{articleCount} articles</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CategoriesPage;
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
import { ArrowRight, Info, Search } from 'lucide-react';
|
||||||
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import { ApiError, getArticles } from '../api/client';
|
||||||
|
import { ArticleCard, getReadTime } from '../components/articles/ArticleCard';
|
||||||
|
import { AuthorAvatar } from '../components/articles/AuthorAvatar';
|
||||||
|
import { CategoryBadge } from '../components/articles/CategoryBadge';
|
||||||
|
import { sampleArticles } from '../data/sample';
|
||||||
|
import type { Article } from '../types';
|
||||||
|
|
||||||
|
type FeedSource = 'api' | 'sample';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Homepage: featured (hero) article, search bar, article grid built from
|
||||||
|
* ArticleCard components, and a pagination placeholder.
|
||||||
|
*
|
||||||
|
* Articles are loaded from `GET /api/v1/articles`; until that backend
|
||||||
|
* endpoint exists the page falls back to sample data (clearly labelled).
|
||||||
|
*/
|
||||||
|
export function Home() {
|
||||||
|
const [articles, setArticles] = useState<Article[]>([]);
|
||||||
|
const [source, setSource] = useState<FeedSource>('sample');
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
getArticles()
|
||||||
|
.then((data) => {
|
||||||
|
if (!active) return;
|
||||||
|
if (data.length > 0) {
|
||||||
|
setArticles(data);
|
||||||
|
setSource('api');
|
||||||
|
} else {
|
||||||
|
setArticles(sampleArticles);
|
||||||
|
setSource('sample');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
if (!active) return;
|
||||||
|
// 404 (endpoint not implemented yet) or network failure: fall back to
|
||||||
|
// sample data so the UI stays useful without a running backend.
|
||||||
|
if (!(error instanceof ApiError)) {
|
||||||
|
console.error('Unexpected error while loading articles:', error);
|
||||||
|
}
|
||||||
|
setArticles(sampleArticles);
|
||||||
|
setSource('sample');
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (active) setLoading(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const filtered = useMemo(() => {
|
||||||
|
const q = query.trim().toLowerCase();
|
||||||
|
if (!q) return articles;
|
||||||
|
return articles.filter(
|
||||||
|
(article) =>
|
||||||
|
article.title.toLowerCase().includes(q) ||
|
||||||
|
article.content.toLowerCase().includes(q),
|
||||||
|
);
|
||||||
|
}, [articles, query]);
|
||||||
|
|
||||||
|
const featured = filtered[0];
|
||||||
|
const publishedAt = (article: Article): string => {
|
||||||
|
const date = article.createdAt instanceof Date ? article.createdAt : new Date(article.createdAt);
|
||||||
|
return Number.isNaN(date.getTime())
|
||||||
|
? ''
|
||||||
|
: date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="container-page">
|
||||||
|
{/* Search / filter bar (client-side filter for now) */}
|
||||||
|
<form
|
||||||
|
role="search"
|
||||||
|
className="mb-8 flex items-center gap-3"
|
||||||
|
onSubmit={(event) => event.preventDefault()}
|
||||||
|
>
|
||||||
|
<label htmlFor="article-search" className="sr-only">
|
||||||
|
Search articles
|
||||||
|
</label>
|
||||||
|
<div className="relative w-full max-w-md">
|
||||||
|
<Search
|
||||||
|
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
id="article-search"
|
||||||
|
type="search"
|
||||||
|
placeholder="Search articles"
|
||||||
|
value={query}
|
||||||
|
onChange={(event) => setQuery(event.target.value)}
|
||||||
|
className="w-full rounded-md border border-slate-300 bg-white py-2 pl-9 pr-3 text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<select
|
||||||
|
aria-label="Filter by category"
|
||||||
|
className="rounded-md border border-slate-300 bg-white py-2 pl-3 pr-8 text-sm text-slate-600"
|
||||||
|
defaultValue=""
|
||||||
|
disabled
|
||||||
|
title="Category filtering arrives with a later milestone"
|
||||||
|
>
|
||||||
|
<option value="">All categories</option>
|
||||||
|
</select>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{source === 'sample' && !loading && (
|
||||||
|
<p
|
||||||
|
data-testid="sample-data-note"
|
||||||
|
className="mb-6 flex items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800"
|
||||||
|
>
|
||||||
|
<Info className="h-4 w-4 shrink-0" aria-hidden="true" />
|
||||||
|
Showing sample data — live articles arrive once the backend article
|
||||||
|
endpoints are available.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Hero: featured article */}
|
||||||
|
{featured && (
|
||||||
|
<section
|
||||||
|
aria-label="Featured article"
|
||||||
|
className="mb-10 overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm"
|
||||||
|
>
|
||||||
|
<div className="grid gap-6 p-6 sm:p-8 md:grid-cols-[2fr,1fr] md:items-center">
|
||||||
|
<div>
|
||||||
|
<div className="mb-3 flex items-center gap-3">
|
||||||
|
<span className="rounded-full bg-blue-600 px-2.5 py-0.5 text-xs font-semibold uppercase tracking-wide text-white">
|
||||||
|
Featured
|
||||||
|
</span>
|
||||||
|
{featured.category && <CategoryBadge category={featured.category} />}
|
||||||
|
</div>
|
||||||
|
<h1 className="mb-3 text-2xl font-bold leading-tight text-slate-900 sm:text-3xl">
|
||||||
|
{featured.title}
|
||||||
|
</h1>
|
||||||
|
<p className="mb-4 text-sm leading-relaxed text-slate-600 sm:text-base">
|
||||||
|
{featured.content}
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-slate-500">
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<AuthorAvatar
|
||||||
|
author={featured.author ?? { name: 'Unknown author' }}
|
||||||
|
size="sm"
|
||||||
|
/>
|
||||||
|
{featured.author?.name ?? 'Unknown author'}
|
||||||
|
</span>
|
||||||
|
<span>{publishedAt(featured)}</span>
|
||||||
|
<span>{getReadTime(featured.content)} min read</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex md:justify-end">
|
||||||
|
<Link to={`/articles/${featured.id}`} className="btn">
|
||||||
|
Read article
|
||||||
|
<ArrowRight className="h-4 w-4" aria-hidden="true" />
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Article grid */}
|
||||||
|
<section aria-label="Latest articles" className="mb-10">
|
||||||
|
<h2 className="mb-4 text-lg font-semibold text-slate-900">Latest articles</h2>
|
||||||
|
{loading ? (
|
||||||
|
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3" aria-busy="true">
|
||||||
|
{[0, 1, 2].map((index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="h-80 animate-pulse rounded-lg border border-slate-200 bg-white p-4"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : filtered.length > 0 ? (
|
||||||
|
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{filtered.map((article) => (
|
||||||
|
<ArticleCard key={article.id} article={article} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="rounded-md border border-dashed border-slate-300 bg-white px-4 py-8 text-center text-sm text-slate-500">
|
||||||
|
No articles match your search.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Pagination placeholder */}
|
||||||
|
<nav aria-label="Pagination" className="flex items-center justify-center gap-2">
|
||||||
|
<button type="button" className="btn-secondary" disabled>
|
||||||
|
Previous
|
||||||
|
</button>
|
||||||
|
<span className="text-sm text-slate-500">Page 1 of 1</span>
|
||||||
|
<button type="button" className="btn-secondary" disabled>
|
||||||
|
Next
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Home;
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { screen } from '@testing-library/react';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { ArticleCard, getReadTime } from '../components/articles/ArticleCard';
|
||||||
|
import type { Article } from '../types';
|
||||||
|
import { renderWithRouter } from './utils';
|
||||||
|
|
||||||
|
const article: Article = {
|
||||||
|
id: 42,
|
||||||
|
title: 'Test article title',
|
||||||
|
content: 'Lorem ipsum dolor sit amet. '.repeat(20),
|
||||||
|
authorId: 1,
|
||||||
|
author: { id: 1, name: 'Jane Doe', email: 'jane@example.com', bio: 'Writer' },
|
||||||
|
categoryId: 2,
|
||||||
|
category: { id: 2, name: 'Science', slug: 'science' },
|
||||||
|
createdAt: '2025-03-01T12:00:00Z',
|
||||||
|
published: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('ArticleCard', () => {
|
||||||
|
it('renders the title, category badge, author and read time', () => {
|
||||||
|
renderWithRouter(<ArticleCard article={article} />);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
screen.getByRole('heading', { level: 3, name: 'Test article title' }),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('category-badge')).toHaveTextContent('Science');
|
||||||
|
expect(screen.getByText('Jane Doe')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/min read/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows author initials in the avatar', () => {
|
||||||
|
renderWithRouter(<ArticleCard article={article} />);
|
||||||
|
expect(screen.getByTestId('author-avatar')).toHaveTextContent('JD');
|
||||||
|
expect(screen.getByTestId('author-avatar')).toHaveAttribute('title', 'Jane Doe');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('links to the article detail route', () => {
|
||||||
|
renderWithRouter(<ArticleCard article={article} />);
|
||||||
|
|
||||||
|
const links = screen.getAllByRole('link');
|
||||||
|
expect(
|
||||||
|
links.some((link) => link.getAttribute('href') === '/articles/42'),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to an unknown author when the author is missing', () => {
|
||||||
|
renderWithRouter(<ArticleCard article={{ ...article, author: undefined }} />);
|
||||||
|
expect(screen.getByText('Unknown author')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits the category badge when no category is present', () => {
|
||||||
|
renderWithRouter(<ArticleCard article={{ ...article, category: undefined }} />);
|
||||||
|
expect(screen.queryByTestId('category-badge')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getReadTime', () => {
|
||||||
|
it('returns a minimum of one minute', () => {
|
||||||
|
expect(getReadTime('a very short piece')).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('estimates two minutes for ~400 words at 200 wpm', () => {
|
||||||
|
expect(getReadTime('word '.repeat(400).trim())).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { fireEvent, screen, within } from '@testing-library/react';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import Header from '../components/ui/Header';
|
||||||
|
import { renderWithRouter } from './utils';
|
||||||
|
|
||||||
|
describe('Header', () => {
|
||||||
|
it('renders the brand with the logo', () => {
|
||||||
|
renderWithRouter(<Header />);
|
||||||
|
const brand = screen.getByRole('link', { name: 'newzy' });
|
||||||
|
expect(brand).toHaveAttribute('href', '/');
|
||||||
|
expect(brand.querySelector('img')).toHaveAttribute('src', expect.stringContaining('logo'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the primary navigation with router links and lucide icons', () => {
|
||||||
|
renderWithRouter(<Header />);
|
||||||
|
|
||||||
|
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||||
|
expect(within(nav).getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
|
||||||
|
expect(within(nav).getByRole('link', { name: /articles/i })).toHaveAttribute('href', '/articles');
|
||||||
|
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveAttribute('href', '/categories');
|
||||||
|
|
||||||
|
// Lucide icons render as inline SVGs (one per nav item).
|
||||||
|
expect(nav.querySelectorAll('svg').length).toBeGreaterThanOrEqual(NAV_ITEM_COUNT);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks the active route in the navigation', () => {
|
||||||
|
renderWithRouter(<Header />, { route: '/categories' });
|
||||||
|
|
||||||
|
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||||
|
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveClass('bg-blue-50');
|
||||||
|
expect(within(nav).getByRole('link', { name: /home/i })).not.toHaveClass('bg-blue-50');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('toggles the mobile menu', () => {
|
||||||
|
renderWithRouter(<Header />);
|
||||||
|
|
||||||
|
// Mobile menu is closed by default.
|
||||||
|
expect(screen.queryByRole('navigation', { name: 'Mobile navigation' })).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Open menu' }));
|
||||||
|
const mobileNav = screen.getByRole('navigation', { name: 'Mobile navigation' });
|
||||||
|
expect(mobileNav).toBeInTheDocument();
|
||||||
|
expect(within(mobileNav).getByRole('link', { name: /articles/i })).toHaveAttribute(
|
||||||
|
'href',
|
||||||
|
'/articles',
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Close menu' }));
|
||||||
|
expect(
|
||||||
|
screen.queryByRole('navigation', { name: 'Mobile navigation' }),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const NAV_ITEM_COUNT = 3;
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { screen } from '@testing-library/react';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import type { Mock } from 'vitest';
|
||||||
|
import { getHealth } from '../api/client';
|
||||||
|
import Layout from '../components/ui/Layout';
|
||||||
|
import { renderWithRouter } from './utils';
|
||||||
|
|
||||||
|
vi.mock('../api/client', () => ({
|
||||||
|
getHealth: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('Layout', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the header, main content area and footer', () => {
|
||||||
|
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||||
|
|
||||||
|
renderWithRouter(
|
||||||
|
<Layout>
|
||||||
|
<p>Page content</p>
|
||||||
|
</Layout>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByRole('banner')).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('main')).toHaveTextContent('Page content');
|
||||||
|
expect(screen.getByRole('contentinfo')).toBeInTheDocument();
|
||||||
|
// Brand is reachable from the layout header.
|
||||||
|
expect(screen.getByRole('link', { name: 'newzy' })).toHaveAttribute('href', '/');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the API as online when the health check succeeds', async () => {
|
||||||
|
(getHealth as Mock).mockResolvedValue({ status: 'ok', version: '0.1.0' });
|
||||||
|
|
||||||
|
renderWithRouter(
|
||||||
|
<Layout>
|
||||||
|
<p>content</p>
|
||||||
|
</Layout>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('api-status')).toHaveTextContent(/api:\s*online/i);
|
||||||
|
expect(getHealth).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the API as offline when the health check fails', async () => {
|
||||||
|
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||||
|
|
||||||
|
renderWithRouter(
|
||||||
|
<Layout>
|
||||||
|
<p>content</p>
|
||||||
|
</Layout>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('api-status')).toHaveTextContent(/api:\s*offline/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { render, screen } from '@testing-library/react';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { AuthorAvatar, initialsOf } from '../../components/articles/AuthorAvatar';
|
||||||
|
|
||||||
|
describe('AuthorAvatar', () => {
|
||||||
|
it('shows initials when no avatar image is set', () => {
|
||||||
|
render(<AuthorAvatar author={{ name: 'Ada Lovelace' }} />);
|
||||||
|
|
||||||
|
const avatar = screen.getByTestId('author-avatar');
|
||||||
|
expect(avatar).toHaveTextContent('AL');
|
||||||
|
expect(avatar).toHaveAttribute('title', 'Ada Lovelace');
|
||||||
|
expect(avatar).toHaveAttribute('aria-label', 'Ada Lovelace');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the avatar image when provided', () => {
|
||||||
|
render(
|
||||||
|
<AuthorAvatar
|
||||||
|
author={{ name: 'Ada Lovelace', avatar: 'https://example.com/ada.png' }}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const image = screen.getByRole('img', { name: 'Ada Lovelace' });
|
||||||
|
expect(image).toHaveAttribute('src', 'https://example.com/ada.png');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supports size variants', () => {
|
||||||
|
const { rerender } = render(<AuthorAvatar author={{ name: 'Ada Lovelace' }} size="lg" />);
|
||||||
|
expect(screen.getByTestId('author-avatar')).toHaveClass('h-12', 'w-12');
|
||||||
|
|
||||||
|
rerender(<AuthorAvatar author={{ name: 'Ada Lovelace' }} size="sm" />);
|
||||||
|
expect(screen.getByTestId('author-avatar')).toHaveClass('h-6', 'w-6');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('initialsOf', () => {
|
||||||
|
it('takes the first letter of the first two words', () => {
|
||||||
|
expect(initialsOf('Grace Hopper')).toBe('GH');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles single names and extra whitespace', () => {
|
||||||
|
expect(initialsOf('Turing')).toBe('T');
|
||||||
|
expect(initialsOf(' Ada Lovelace ')).toBe('AL');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { render, screen } from '@testing-library/react';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import CategoryBadge from '../../components/articles/CategoryBadge';
|
||||||
|
|
||||||
|
describe('CategoryBadge', () => {
|
||||||
|
it('renders the category name', () => {
|
||||||
|
render(<CategoryBadge category={{ name: 'Technology', slug: 'technology' }} />);
|
||||||
|
expect(screen.getByTestId('category-badge')).toHaveTextContent('Technology');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies the color tone for known slugs', () => {
|
||||||
|
render(<CategoryBadge category={{ name: 'Technology', slug: 'technology' }} />);
|
||||||
|
expect(screen.getByTestId('category-badge')).toHaveClass('bg-blue-100');
|
||||||
|
|
||||||
|
render(<CategoryBadge category={{ name: 'Science', slug: 'science' }} />);
|
||||||
|
expect(screen.getAllByTestId('category-badge')[1]).toHaveClass('bg-green-100');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to a neutral tone for unknown slugs', () => {
|
||||||
|
render(<CategoryBadge category={{ name: 'Mystery', slug: 'mystery' }} />);
|
||||||
|
expect(screen.getByTestId('category-badge')).toHaveClass('bg-slate-100');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts extra classes via the className prop', () => {
|
||||||
|
render(
|
||||||
|
<CategoryBadge
|
||||||
|
category={{ name: 'Culture', slug: 'culture' }}
|
||||||
|
className="text-lg"
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('category-badge')).toHaveClass('text-lg');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
/**
|
||||||
|
* Vitest setup: registers jest-dom matchers and cleans up the DOM after
|
||||||
|
* every test (React Testing Library auto-cleanup needs this when globals
|
||||||
|
* are disabled).
|
||||||
|
*/
|
||||||
|
import '@testing-library/jest-dom/vitest';
|
||||||
|
import { cleanup } from '@testing-library/react';
|
||||||
|
import { afterEach } from 'vitest';
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { render, type RenderOptions } from '@testing-library/react';
|
||||||
|
import type { ReactElement } from 'react';
|
||||||
|
import { MemoryRouter } from 'react-router-dom';
|
||||||
|
|
||||||
|
export interface RenderWithRouterOptions extends Omit<RenderOptions, 'wrapper'> {
|
||||||
|
/** Initial route (path only, e.g. "/articles/1"). */
|
||||||
|
route?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render helper that wraps the UI in a MemoryRouter so components using
|
||||||
|
* react-router-dom (Link, NavLink, useParams) can be tested in isolation.
|
||||||
|
*/
|
||||||
|
export function renderWithRouter(ui: ReactElement, options: RenderWithRouterOptions = {}) {
|
||||||
|
const { route = '/', ...renderOptions } = options;
|
||||||
|
|
||||||
|
return render(
|
||||||
|
<MemoryRouter
|
||||||
|
initialEntries={[route]}
|
||||||
|
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||||
|
>
|
||||||
|
{ui}
|
||||||
|
</MemoryRouter>,
|
||||||
|
renderOptions,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
/**
|
||||||
|
* Core domain types for the newzy frontend.
|
||||||
|
*
|
||||||
|
* These interfaces mirror the backend models (see `backend/models/`) and the
|
||||||
|
* API schemas (see `backend/schemas/`). Note the backend returns snake_case
|
||||||
|
* JSON (e.g. `author_id`, `created_at`); `src/api/client.ts` maps those
|
||||||
|
* payloads onto the camelCase interfaces defined here.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface Article {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
content: string;
|
||||||
|
authorId: number;
|
||||||
|
author?: Author;
|
||||||
|
categoryId: number;
|
||||||
|
category?: Category;
|
||||||
|
createdAt: Date | string;
|
||||||
|
published: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Author {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
bio?: string;
|
||||||
|
avatar?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Category {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Envelope used by frontend API helpers for successful responses. */
|
||||||
|
export interface ApiResponse<T> {
|
||||||
|
success: boolean;
|
||||||
|
data?: T;
|
||||||
|
error?: string;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Standard error envelope returned by the FastAPI backend for non-2xx. */
|
||||||
|
export interface ApiErrorPayload {
|
||||||
|
detail: string;
|
||||||
|
code: string;
|
||||||
|
errors?: Array<Record<string, unknown>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Payload of `GET /api/v1/health` (and `GET /health`). */
|
||||||
|
export interface HealthResponse {
|
||||||
|
status: string;
|
||||||
|
version: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Payload of `GET /api/v1/version`. */
|
||||||
|
export interface VersionResponse {
|
||||||
|
app: string;
|
||||||
|
version: string;
|
||||||
|
}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import defaultTheme from 'tailwindcss/defaultTheme';
|
||||||
|
|
||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
export default {
|
||||||
|
content: ['./index.html', './src/**/*.{ts,tsx}'],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
fontFamily: {
|
||||||
|
sans: ['Inter', 'system-ui', ...defaultTheme.fontFamily.sans],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
};
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode (Vite) */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true
|
||||||
|
},
|
||||||
|
"include": ["src"],
|
||||||
|
"references": [{ "path": "./tsconfig.node.json" }]
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"composite": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"strict": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts", "vitest.config.ts", "playwright.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
import { defineConfig } from 'vite';
|
||||||
|
|
||||||
|
// https://vitejs.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
// Base path used for all generated asset URLs.
|
||||||
|
base: '/',
|
||||||
|
build: {
|
||||||
|
// Production bundle output directory (served by Nginx in Docker).
|
||||||
|
outDir: 'dist',
|
||||||
|
sourcemap: false,
|
||||||
|
target: 'es2020',
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
// Development server.
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
// Forward API calls to the FastAPI backend during development.
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:8000',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
preview: {
|
||||||
|
// `vite preview` (used by the Playwright E2E webServer).
|
||||||
|
port: 4173,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:8000',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/// <reference types="vitest" />
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
import { defineConfig } from 'vitest/config';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
test: {
|
||||||
|
environment: 'jsdom',
|
||||||
|
setupFiles: ['./src/tests/setup.ts'],
|
||||||
|
include: ['src/tests/**/*.test.{ts,tsx}'],
|
||||||
|
exclude: ['node_modules', 'dist', 'playwright'],
|
||||||
|
css: false,
|
||||||
|
globals: false,
|
||||||
|
coverage: {
|
||||||
|
provider: 'v8',
|
||||||
|
reporter: ['text', 'html', 'lcov'],
|
||||||
|
include: ['src/components/**', 'src/pages/**'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
# M2: Setup Backend
|
||||||
|
|
||||||
|
## Prompt
|
||||||
|
|
||||||
|
Create the backend infrastructure for **newzy** news web application using Python FastAPI. Follow these steps:
|
||||||
|
|
||||||
|
1. Set up project structure in `backend/` folder:
|
||||||
|
```
|
||||||
|
newzy/
|
||||||
|
├── backend/
|
||||||
|
│ ├── api/
|
||||||
|
│ │ └── v1/
|
||||||
|
│ │ └── __init__.py
|
||||||
|
│ ├── core/
|
||||||
|
│ │ └── __init__.py
|
||||||
|
│ ├── db/
|
||||||
|
│ │ └── session.py
|
||||||
|
│ ├── models/
|
||||||
|
│ │ └── __init__.py
|
||||||
|
│ ├── schemas/
|
||||||
|
│ │ └── __init__.py
|
||||||
|
│ ├── tests/
|
||||||
|
│ │ ├── conftest.py
|
||||||
|
│ │ ├── test_health.py
|
||||||
|
│ │ ├── test_version.py
|
||||||
|
│ │ └── test_models.py
|
||||||
|
│ ├── main.py
|
||||||
|
│ ├── config.py
|
||||||
|
│ ├── requirements.txt
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ ├── .gitignore
|
||||||
|
│ ├── pytest.ini
|
||||||
|
│ └── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create FastAPI application in `backend/main.py` with:
|
||||||
|
- Health check endpoint (`GET /health`)
|
||||||
|
- Version endpoint (`GET /api/v1/version`)
|
||||||
|
|
||||||
|
3. Set up SQLAlchemy database session using SQLite (configured for Docker volume persistence)
|
||||||
|
|
||||||
|
4. Define Pydantic schemas for basic models (Article, Author, Category)
|
||||||
|
|
||||||
|
5. Configure `requirements.txt` with:
|
||||||
|
- FastAPI
|
||||||
|
- uvicorn
|
||||||
|
- SQLAlchemy
|
||||||
|
- pydantic
|
||||||
|
- python-multipart
|
||||||
|
- pytest and pytest-asyncio for testing
|
||||||
|
|
||||||
|
6. Create initial database models for:
|
||||||
|
- Article (title, content, author_id, category_id, created_at, published)
|
||||||
|
- Author (name, email, bio)
|
||||||
|
- Category (name, slug)
|
||||||
|
|
||||||
|
7. Add proper exception handling and error responses
|
||||||
|
|
||||||
|
8. Document API endpoints in `backend/README.md` with examples
|
||||||
|
|
||||||
|
9. Create `.gitignore` to exclude Python artifacts, env files, and IDE configs
|
||||||
|
|
||||||
|
10. Create `Dockerfile` for containerization with:
|
||||||
|
- Base Python image
|
||||||
|
- Install requirements
|
||||||
|
- Copy application code
|
||||||
|
- Expose port 8000
|
||||||
|
- CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
|
|
||||||
|
11. Add `pytest.ini` with test configuration and coverage settings
|
||||||
|
|
||||||
|
12. Create unit tests in `backend/tests/`:
|
||||||
|
- Test health endpoint returns 200 OK
|
||||||
|
- Test version endpoint returns correct format
|
||||||
|
- Test model instantiation and database operations
|
||||||
|
- Use pytest fixtures for database setup/teardown
|
||||||
|
|
||||||
|
13. Add docker-compose.yml at project root with backend service
|
||||||
|
|
||||||
|
Remember: Focus ONLY on backend infrastructure. No frontend implementation required.
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
This milestone sets up the FastAPI backend for newzy news application using Python. The scope includes database configuration, API structure, core models, and basic endpoints—no complex business logic or integration with other services.
|
||||||
|
|
||||||
|
**Purpose**: Create a functional REST API backbone ready for feature development in subsequent milestones.
|
||||||
|
|
||||||
|
**Target Audience**: Backend developers joining the project who need to understand and extend the API.
|
||||||
|
|
||||||
|
**Expected Outcomes**: A containerized FastAPI server with database connectivity, core models defined, documented endpoints, and comprehensive unit tests demonstrating proper implementation.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] FastAPI application created in `backend/main.py`
|
||||||
|
- [ ] SQLAlchemy session configured with SQLite backend
|
||||||
|
- [ ] Database models defined: Article, Author, Category
|
||||||
|
- [ ] Pydantic schemas implemented for all models
|
||||||
|
- [ ] Health check endpoint (`GET /health`) returns 200 OK
|
||||||
|
- [ ] Version endpoint (`GET /api/v1/version`) returns application version
|
||||||
|
- [ ] `requirements.txt` lists all Python dependencies including testing libs
|
||||||
|
- [ ] Proper error handling with standardized response format
|
||||||
|
- [ ] `backend/README.md` documents API endpoints with examples
|
||||||
|
- [ ] `.gitignore` file created with appropriate exclusions
|
||||||
|
- [ ] `Dockerfile` creates runnable container image
|
||||||
|
- [ ] Unit tests in `backend/tests/` covering health, version, and models
|
||||||
|
- [ ] pytest.ini configured for test discovery and coverage
|
||||||
|
- [ ] Code follows FastAPI and SQLAlchemy best practices
|
||||||
|
|
||||||
|
## Technical Details
|
||||||
|
|
||||||
|
### Project Root Structure
|
||||||
|
```
|
||||||
|
project-root/
|
||||||
|
├── backend/
|
||||||
|
│ ├── api/
|
||||||
|
│ │ └── v1/
|
||||||
|
│ │ └── __init__.py
|
||||||
|
│ ├── core/
|
||||||
|
│ ├── db/
|
||||||
|
│ ├── models/
|
||||||
|
│ ├── schemas/
|
||||||
|
│ ├── tests/
|
||||||
|
│ │ ├── conftest.py
|
||||||
|
│ │ ├── test_health.py
|
||||||
|
│ │ ├── test_version.py
|
||||||
|
│ │ └── test_models.py
|
||||||
|
│ ├── main.py
|
||||||
|
│ ├── config.py
|
||||||
|
│ ├── requirements.txt
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ ├── .gitignore
|
||||||
|
│ ├── pytest.ini
|
||||||
|
│ └── README.md
|
||||||
|
├── LICENSE # MIT License
|
||||||
|
├── README.md
|
||||||
|
└── CONTRIBUTING.md
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database Schema (SQLite)
|
||||||
|
|
||||||
|
**Article Model:**
|
||||||
|
- `id`: Integer, primary key
|
||||||
|
- `title`: String(200), unique
|
||||||
|
- `content`: Text
|
||||||
|
- `author_id`: Integer, foreign key to Author
|
||||||
|
- `category_id`: Integer, foreign key to Category
|
||||||
|
- `created_at`: DateTime
|
||||||
|
- `published`: Boolean, default False
|
||||||
|
|
||||||
|
**Author Model:**
|
||||||
|
- `id`: Integer, primary key
|
||||||
|
- `name`: String(100), unique
|
||||||
|
- `email`: String(255), unique
|
||||||
|
- `bio`: Text (nullable)
|
||||||
|
|
||||||
|
**Category Model:**
|
||||||
|
- `id`: Integer, primary key
|
||||||
|
- `name`: String(100), unique
|
||||||
|
- `slug`: String(100), unique
|
||||||
|
|
||||||
|
### Backend API Endpoints
|
||||||
|
|
||||||
|
| Method | Path | Description |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| GET | /health | Health check endpoint |
|
||||||
|
| GET | /api/v1/version | Returns application version |
|
||||||
|
| GET | /api/v1/health | Alternative health check path |
|
||||||
|
|
||||||
|
### .gitignore Contents for backend/
|
||||||
|
```python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.egg-info/
|
||||||
|
.env
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
|
Dockerfile
|
||||||
|
.docker/
|
||||||
|
.DS_Store
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*~
|
||||||
|
.coverage
|
||||||
|
htmlcov/
|
||||||
|
.pytest_cache/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dockerfile
|
||||||
|
```dockerfile
|
||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
# Copy application code
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
# Run application
|
||||||
|
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### pytest.ini Configuration
|
||||||
|
```ini
|
||||||
|
[pytest]
|
||||||
|
testpaths = tests
|
||||||
|
python_files = test_*.py
|
||||||
|
python_classes = Test*
|
||||||
|
python_functions = test_*
|
||||||
|
asyncio_mode = auto
|
||||||
|
addopts = -v --cov=. --cov-report=term-missing
|
||||||
|
filterwarnings = ignore::DeprecationWarning
|
||||||
|
```
|
||||||
|
|
||||||
|
### docker-compose.yml (project root)
|
||||||
|
```yaml
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
backend:
|
||||||
|
build: ./backend
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
volumes:
|
||||||
|
- ./data/db:/app/data/db
|
||||||
|
environment:
|
||||||
|
- DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||||
|
```
|
||||||
|
|
||||||
|
### Unit Tests Overview
|
||||||
|
|
||||||
|
**test_health.py:**
|
||||||
|
- Test health endpoint returns 200 status code
|
||||||
|
- Verify response contains expected JSON structure
|
||||||
|
- Test alternative /api/v1/health path
|
||||||
|
|
||||||
|
**test_version.py:**
|
||||||
|
- Test version endpoint returns valid version string
|
||||||
|
- Response format validation (e.g., "v0.1.0")
|
||||||
|
|
||||||
|
**test_models.py:**
|
||||||
|
- Test Article model creation and commit to database
|
||||||
|
- Test Author model creation with unique constraints
|
||||||
|
- Test Category model slug generation
|
||||||
|
- Verify foreign key relationships work correctly
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
- Environment variables for database URL (DATABASE_URL)
|
||||||
|
- Docker volume configuration: `/data/db` mapped to SQLite file
|
||||||
|
- CORS enabled for frontend development
|
||||||
|
- Uvicorn workers configured for production deployment
|
||||||
|
- Pytest configured for coverage reporting
|
||||||
|
|
||||||
|
## QA Notes
|
||||||
|
|
||||||
|
### Testing Checklist
|
||||||
|
- [ ] Application starts without errors
|
||||||
|
- [ ] Health endpoint returns 200 OK with JSON response
|
||||||
|
- [ ] Version endpoint returns correct format (version string)
|
||||||
|
- [ ] Database connection successful
|
||||||
|
- [ ] Models can be instantiated and committed
|
||||||
|
- [ ] Error responses follow standardized format
|
||||||
|
- [ ] No unhandled exceptions in basic operations
|
||||||
|
- [ ] Docker container builds successfully
|
||||||
|
- [ ] Container runs and serves endpoints
|
||||||
|
- [ ] pytest discovers and runs all test files
|
||||||
|
- [ ] All unit tests pass (100% expected coverage)
|
||||||
|
|
||||||
|
### Performance Considerations
|
||||||
|
- Single-threaded async mode for development (uvicorn workers = 1)
|
||||||
|
- SQLite file-based storage (no connection pool needed yet)
|
||||||
|
- Lazy database session management
|
||||||
|
- Docker Compose enables easy local development setup
|
||||||
|
- Tests use fast in-memory or temporary database files
|
||||||
|
|
||||||
|
### Security Notes
|
||||||
|
- Password hashing to be implemented in future milestones
|
||||||
|
- Authentication mechanism TBD
|
||||||
|
- CORS configuration should be validated before production
|
||||||
|
- Environment variables for secrets should use .env files
|
||||||
|
- pytest cache directories excluded from git
|
||||||
|
|
||||||
|
### Known Issues / Limitations
|
||||||
|
- No input validation beyond Pydantic schemas
|
||||||
|
- No rate limiting implemented
|
||||||
|
- Database schema not yet optimized for performance
|
||||||
|
- Missing pagination and filtering on article endpoints
|
||||||
|
- SQLite not suitable for high-concurrency production workloads
|
||||||
|
- Tests don't cover edge cases or error scenarios extensively
|
||||||
|
|
||||||
|
### Success Metrics
|
||||||
|
- Application starts in under 10 seconds locally
|
||||||
|
- Health check responds within 100ms
|
||||||
|
- All models query successfully without errors
|
||||||
|
- Docker image builds and runs cleanly
|
||||||
|
- README examples work as documented
|
||||||
|
- Unit tests achieve >=70% code coverage on core modules
|
||||||
|
- All tests complete in under 30 seconds
|
||||||
@@ -0,0 +1,419 @@
|
|||||||
|
# M3: Setup Frontend
|
||||||
|
|
||||||
|
## Prompt
|
||||||
|
|
||||||
|
Create the frontend infrastructure for **newzy** news web application using React + TypeScript with Vite. Follow these steps:
|
||||||
|
|
||||||
|
1. Set up project structure in `frontend/` folder with clear separation between pages and components:
|
||||||
|
```
|
||||||
|
newzy/
|
||||||
|
├── frontend/
|
||||||
|
│ ├── public/
|
||||||
|
│ │ └── index.html # Vite entry HTML file
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── assets/
|
||||||
|
│ │ │ ├── styles/
|
||||||
|
│ │ │ │ └── globals.css # Global styles
|
||||||
|
│ │ │ └── logo.svg # Brand logo (placeholder)
|
||||||
|
│ │ ├── components/
|
||||||
|
│ │ │ ├── ui/
|
||||||
|
│ │ │ │ ├── Header.tsx # Main navigation header with lucide icons
|
||||||
|
│ │ │ │ └── Layout.tsx # Wrapper component with layout structure
|
||||||
|
│ │ │ └── articles/
|
||||||
|
│ │ │ ├── ArticleCard.tsx # Reusable article display component
|
||||||
|
│ │ │ ├── AuthorAvatar.tsx # Author profile component
|
||||||
|
│ │ │ └── CategoryBadge.tsx # Category label component
|
||||||
|
│ │ ├── pages/
|
||||||
|
│ │ │ ├── Home.tsx # Homepage with article feed layout
|
||||||
|
│ │ │ ├── ArticlePage.tsx # Individual article view (placeholder)
|
||||||
|
│ │ │ └── CategoriesPage.tsx # Categories listing page (placeholder)
|
||||||
|
│ │ ├── types/
|
||||||
|
│ │ │ └── index.ts # TypeScript interfaces
|
||||||
|
│ │ ├── api/
|
||||||
|
│ │ │ └── client.ts # API request wrapper
|
||||||
|
│ │ ├── tests/
|
||||||
|
│ │ │ ├── Header.test.tsx
|
||||||
|
│ │ │ ├── ArticleCard.test.tsx
|
||||||
|
│ │ │ └── components/
|
||||||
|
│ │ ├── App.tsx # Root component with React Router setup
|
||||||
|
│ │ └── main.tsx # React entry point
|
||||||
|
│ ├── playwright/
|
||||||
|
│ │ └── e2e/
|
||||||
|
│ │ ├── home.spec.ts # E2E test for homepage
|
||||||
|
│ │ └── api.spec.ts # E2E test for API interactions
|
||||||
|
│ ├── .gitignore
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ ├── docker-compose.yml # Frontend service config
|
||||||
|
│ ├── package.json # Include react-router-dom dependency
|
||||||
|
│ ├── tsconfig.json
|
||||||
|
│ ├── vite.config.ts
|
||||||
|
│ └── README.md # Setup and API documentation
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Initialize Vite project with React, TypeScript template:
|
||||||
|
- Use Node.js 18 or later
|
||||||
|
- Install dependencies including lucide-react for icons AND react-router-dom for routing:
|
||||||
|
- react, react-dom, typescript, @types/react, @types/react-dom, vite
|
||||||
|
- lucide-react (for UI icons)
|
||||||
|
- react-router-dom v6.x (for client-side routing)
|
||||||
|
- class-variance-authority, clsx, tailwind-merge (for utility classes)
|
||||||
|
|
||||||
|
3. Install and configure Playwright and Vitest:
|
||||||
|
- @playwright/test for E2E testing
|
||||||
|
- vitest for unit testing
|
||||||
|
- @testing-library/react for component testing
|
||||||
|
- Run npx playwright install
|
||||||
|
|
||||||
|
4. Configure Vite with:
|
||||||
|
- Base path configuration
|
||||||
|
- Build output directory (dist/)
|
||||||
|
- Development server on port 5173
|
||||||
|
- React Router DOM plugin configuration if using router v6 dynamic imports
|
||||||
|
|
||||||
|
5. Create TypeScript type definitions in `src/types/`:
|
||||||
|
- Article interface (id, title, content, author, category, published, createdAt)
|
||||||
|
- Author interface (id, name, email, bio)
|
||||||
|
- Category interface (id, name, slug)
|
||||||
|
- API response types
|
||||||
|
|
||||||
|
6. Create UI components with lucide-react icons in `src/components/ui/`:
|
||||||
|
- **Header.tsx**:
|
||||||
|
- Logo/text brand representation
|
||||||
|
- Navigation links that use React Router for navigation
|
||||||
|
- Use Lucide icons: Home, FileText, Settings for navigation items
|
||||||
|
- Responsive design with mobile menu consideration
|
||||||
|
|
||||||
|
- **Layout.tsx**:
|
||||||
|
- Wrapper component for page structure
|
||||||
|
- Header integration via routing-aware navigation
|
||||||
|
- Content area placeholder
|
||||||
|
- Footer section placeholder
|
||||||
|
|
||||||
|
7. Create article-specific components in `src/components/articles/`:
|
||||||
|
- **ArticleCard.tsx**: Displays article summary with thumbnail placeholder, title, author info, category badge, read time
|
||||||
|
- **AuthorAvatar.tsx**: Shows author initials or profile image, hover tooltip with name
|
||||||
|
- **CategoryBadge.tsx**: Color-coded category pill component
|
||||||
|
|
||||||
|
8. Create page components in `src/pages/`:
|
||||||
|
- **Home.tsx**:
|
||||||
|
- Hero section with featured article
|
||||||
|
- Article grid layout using ArticleCard
|
||||||
|
- Pagination or infinite scroll placeholder
|
||||||
|
- Search/filter bar placeholder
|
||||||
|
|
||||||
|
- **ArticlePage.tsx** and **CategoriesPage.tsx**: Basic layouts for future pages
|
||||||
|
|
||||||
|
9. Set up React Router in `App.tsx` with:
|
||||||
|
- BrowserRouter wrapper at root level
|
||||||
|
- Route definitions mapping pages to URLs
|
||||||
|
- Proper route-to-page component imports
|
||||||
|
- Link navigation using react-router-dom's `<Link>` component (not anchor tags)
|
||||||
|
|
||||||
|
10. Set up API client in `src/api/client.ts`:
|
||||||
|
- Base URL configuration (relative path /api)
|
||||||
|
- Fetch wrapper with error handling
|
||||||
|
- Type-safe request/response functions
|
||||||
|
|
||||||
|
11. Create component tests using Vitest:
|
||||||
|
- Test Header renders correctly with lucide icons and routing links
|
||||||
|
- Test ArticleCard displays data correctly
|
||||||
|
- Test Layout structure is properly implemented
|
||||||
|
- Use @testing-library/react for rendering
|
||||||
|
|
||||||
|
12. Create Playwright E2E tests:
|
||||||
|
- Test home page accessibility and layout
|
||||||
|
- Test article list renders with data
|
||||||
|
- Test navigation between pages works (via React Router Links)
|
||||||
|
|
||||||
|
13. Create `package.json` scripts:
|
||||||
|
- dev, build, preview, test, e2e, lint
|
||||||
|
|
||||||
|
14. Create `.gitignore` to exclude node_modules, dist/, .env files, IDE configs, playwright trace files
|
||||||
|
|
||||||
|
15. Create `Dockerfile` with Nginx for serving static files in production (multi-stage)
|
||||||
|
|
||||||
|
16. Update `docker-compose.yml` at project root with frontend service:
|
||||||
|
- Port mapping 3000:80
|
||||||
|
- Links to backend service for API calls
|
||||||
|
|
||||||
|
17. Document setup process in `frontend/README.md` with examples and lucide-react icon documentation
|
||||||
|
|
||||||
|
18. Configure ESLint rules for React, TypeScript, and react-router best practices
|
||||||
|
|
||||||
|
Remember: Focus ONLY on frontend infrastructure. No complex UI features required yet.
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
This milestone sets up the React + TypeScript frontend for newzy news application using Vite as the build tool. The scope includes project scaffolding, lucide-react icons integration, React Router setup for navigation, type definitions, properly structured components, and comprehensive testing setup with Playwright E2E tests—no complex UI implementations or user interactions.
|
||||||
|
|
||||||
|
**Purpose**: Create a responsive, type-safe frontend ready to consume the backend API built in M2, with robust test coverage from both unit and E2E perspectives.
|
||||||
|
|
||||||
|
**Target Audience**: Frontend developers who need to understand the structure and extend components for features in subsequent milestones.
|
||||||
|
|
||||||
|
**Expected Outcomes**: A functioning React application that can load from browser or Docker container, with lucide-react icons integrated, React Router configured for client-side navigation, typed interfaces matching backend models, properly separated page and component code, basic page layout in place, and a complete testing setup (unit tests + Playwright E2E).
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] Vite project initialized with React, TypeScript, lucide-react, AND react-router-dom v6.x
|
||||||
|
- [ ] Project structure includes: public/, src/, assets/, components/, pages/, types/, api/, tests/ folders
|
||||||
|
- [ ] Clear separation between `pages/` (page-level routing) and `components/` (reusable UI)
|
||||||
|
- [ ] React Router DOM properly configured in App.tsx with BrowserRouter wrapper
|
||||||
|
- [ ] Route definitions mapped to page components in src/pages/
|
||||||
|
- [ ] lucide-react installed with icons: Home, FileText, Settings, Search
|
||||||
|
- [ ] TypeScript type definitions for Article, Author, Category models
|
||||||
|
- [ ] Header component created with lucide icons and React Router navigation links
|
||||||
|
- [ ] Layout wrapper component implemented with proper structure
|
||||||
|
- [ ] Reusable article components: ArticleCard, AuthorAvatar, CategoryBadge
|
||||||
|
- [ ] Page components: Home.tsx with article grid layout using router Links
|
||||||
|
- [ ] API client configured with base URL and fetch wrapper
|
||||||
|
- [ ] Unit tests in src/tests/ using Vitest (react-testing-library)
|
||||||
|
- [ ] Playwright E2E tests in playwright/e2e/ covering core flows
|
||||||
|
- [ ] package.json has dev, build, preview, test, e2e scripts working correctly
|
||||||
|
- [ ] .gitignore excludes node_modules, dist/, IDE configs, and playwright artifacts
|
||||||
|
- [ ] Dockerfile builds production-ready static files with Nginx serving
|
||||||
|
- [ ] docker-compose.yml includes frontend service linked to backend
|
||||||
|
- [ ] ESLint rules configured and passing for react-router best practices
|
||||||
|
|
||||||
|
## Technical Details
|
||||||
|
|
||||||
|
### Project Root Structure
|
||||||
|
```
|
||||||
|
newzy/
|
||||||
|
├── frontend/
|
||||||
|
│ ├── public/
|
||||||
|
│ │ └── index.html # Vite entry HTML file
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── assets/
|
||||||
|
│ │ │ ├── styles/
|
||||||
|
│ │ │ │ └── globals.css # Tailwind + global styles
|
||||||
|
│ │ │ └── logo.svg # Brand logo (placeholder)
|
||||||
|
│ │ ├── components/
|
||||||
|
│ │ │ ├── ui/ # Generic UI components with lucide icons
|
||||||
|
│ │ │ │ ├── Header.tsx # Navigation with icons and router Links
|
||||||
|
│ │ │ │ └── Layout.tsx # Page wrapper layout
|
||||||
|
│ │ │ └── articles/ # Domain-specific components
|
||||||
|
│ │ │ ├── ArticleCard.tsx # Article preview component
|
||||||
|
│ │ │ ├── AuthorAvatar.tsx # Author profile indicator
|
||||||
|
│ │ │ └── CategoryBadge.tsx # Category label pill
|
||||||
|
│ │ ├── pages/ # Page-level components (routes)
|
||||||
|
│ │ │ ├── Home.tsx # Homepage with article feed
|
||||||
|
│ │ │ ├── ArticlePage.tsx # Individual article view
|
||||||
|
│ │ │ └── CategoriesPage.tsx # Categories listing page
|
||||||
|
│ │ ├── types/
|
||||||
|
│ │ │ └── index.ts # TypeScript interfaces
|
||||||
|
│ │ ├── api/
|
||||||
|
│ │ │ └── client.ts # API request wrapper
|
||||||
|
│ │ ├── tests/ # Unit test files (Vitest)
|
||||||
|
│ │ │ ├── Header.test.tsx
|
||||||
|
│ │ │ ├── ArticleCard.test.tsx
|
||||||
|
│ │ │ └── components/
|
||||||
|
│ │ ├── App.tsx # Root with BrowserRouter and routes
|
||||||
|
│ │ └── main.tsx # React entry point
|
||||||
|
│ ├── playwright/
|
||||||
|
│ │ └── e2e/ # E2E tests (Playwright)
|
||||||
|
│ │ ├── home.spec.ts # Homepage flow test
|
||||||
|
│ │ └── api.spec.ts # API integration test
|
||||||
|
│ ├── .gitignore
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ ├── docker-compose.yml # Frontend service config
|
||||||
|
│ ├── package.json # Dependencies including react-router-dom
|
||||||
|
│ ├── tsconfig.json
|
||||||
|
│ ├── vite.config.ts
|
||||||
|
│ └── README.md # Setup and API documentation
|
||||||
|
├── backend/ # Backend from M2
|
||||||
|
├── LICENSE # MIT License
|
||||||
|
├── README.md # Main project docs
|
||||||
|
└── docker-compose.yml # Full application orchestration
|
||||||
|
```
|
||||||
|
|
||||||
|
### TypeScript Type Definitions
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// src/types/index.ts
|
||||||
|
|
||||||
|
export interface Article {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
content: string;
|
||||||
|
authorId: number;
|
||||||
|
author?: Author;
|
||||||
|
categoryId: number;
|
||||||
|
category?: Category;
|
||||||
|
createdAt: Date | string;
|
||||||
|
published: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Author {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
bio?: string;
|
||||||
|
avatar?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Category {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiResponse<T> {
|
||||||
|
success: boolean;
|
||||||
|
data?: T;
|
||||||
|
error?: string;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### package.json Dependencies
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"dependencies": {
|
||||||
|
"react": "^18.2.0",
|
||||||
|
"react-dom": "^18.2.0",
|
||||||
|
"react-router-dom": "^6.20.0", /* ← React Router v6.x */
|
||||||
|
"typescript": "^5.0.0",
|
||||||
|
"@types/react": "^18.2.0",
|
||||||
|
"@types/react-dom": "^18.2.0",
|
||||||
|
"vite": "^4.4.0",
|
||||||
|
"lucide-react": "^0.263.0",
|
||||||
|
"class-variance-authority": "^0.7.0",
|
||||||
|
"clsx": "^2.0.0",
|
||||||
|
"tailwind-merge": "^2.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@testing-library/react": "^14.0.0",
|
||||||
|
"@playwright/test": "^1.39.0",
|
||||||
|
"vitest": "^0.34.0",
|
||||||
|
"@vitejs/plugin-react": "^4.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### React Router Configuration in App.tsx
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
|
||||||
|
import Home from './pages/Home';
|
||||||
|
import ArticlePage from './pages/ArticlePage';
|
||||||
|
import CategoriesPage from './pages/CategoriesPage';
|
||||||
|
import Layout from './components/ui/Layout';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<BrowserRouter>
|
||||||
|
<Layout>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/" element={<Home />} />
|
||||||
|
<Route path="/articles" element={<ArticlePage />} />
|
||||||
|
<Route path="/categories" element={<CategoriesPage />} />
|
||||||
|
</Routes>
|
||||||
|
</Layout>
|
||||||
|
</BrowserRouter>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Header Component with React Router Links
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Home, FileText, Settings } from 'lucide-react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
|
||||||
|
interface HeaderProps {}
|
||||||
|
|
||||||
|
export function Header({}: HeaderProps) {
|
||||||
|
return (
|
||||||
|
<header className="nav">
|
||||||
|
<h1>newzy</h1>
|
||||||
|
<nav>
|
||||||
|
{/* Navigation uses react-router-dom Link, not anchor tags */}
|
||||||
|
<Link to="/">
|
||||||
|
<Home className="w-5 h-5" />
|
||||||
|
</Link>
|
||||||
|
<Link to="/articles">
|
||||||
|
<FileText className="w-5 h-5" />
|
||||||
|
</Link>
|
||||||
|
<Link to="/categories">
|
||||||
|
<Settings className="w-5 h-5" />
|
||||||
|
</Link>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Page Separation Strategy
|
||||||
|
|
||||||
|
**pages/ (routing - one per route):**
|
||||||
|
- `Home.tsx` → `/` (main landing page with featured article)
|
||||||
|
- `ArticlePage.tsx` → `/articles/:id` (individual article view with useParams)
|
||||||
|
- `CategoriesPage.tsx` → `/categories` (list of categories placeholder)
|
||||||
|
|
||||||
|
**components/ui/ (generic UI with icons):**
|
||||||
|
- `Header.tsx` → Navigation with lucide icons AND React Router `<Link>` components
|
||||||
|
- `Layout.tsx` → Page wrapper structure accepting props from App routes
|
||||||
|
|
||||||
|
**components/articles/ (domain-specific):**
|
||||||
|
- `ArticleCard.tsx` → Article preview component for Home page
|
||||||
|
- `AuthorAvatar.tsx` → Author profile indicator
|
||||||
|
- `CategoryBadge.tsx` → Category label pill
|
||||||
|
|
||||||
|
## QA Notes
|
||||||
|
|
||||||
|
### Unit Testing Checklist (Vitest + React Testing Library)
|
||||||
|
- [ ] Tests discover and run correctly with `npm test`
|
||||||
|
- [ ] Header renders with lucide icons and router Links correctly
|
||||||
|
- [ ] Layout component structure verified with routing context available
|
||||||
|
- [ ] ArticleCard displays data properly
|
||||||
|
- [ ] Component props are type-safe
|
||||||
|
- [ ] Test coverage >50% on tested components
|
||||||
|
|
||||||
|
### E2E Testing Checklist (Playwright)
|
||||||
|
- [ ] Playwright configured in playwright.config.ts
|
||||||
|
- [ ] Tests discover and run with `npm run e2e`
|
||||||
|
- [ ] Home page accessibility verified (a11y checks pass for Links)
|
||||||
|
- [ ] Article list renders with data
|
||||||
|
- [ ] Navigation between pages works via React Router Links (not anchor tags)
|
||||||
|
- [ ] API requests complete successfully via browser
|
||||||
|
- [ ] Browser console has no errors during E2E tests
|
||||||
|
- [ ] Tests use proper selectors for routing elements
|
||||||
|
|
||||||
|
### Performance Considerations
|
||||||
|
- Vite uses ESBuild for fast HMR during development
|
||||||
|
- TypeScript checks on build, not incremental dev
|
||||||
|
- Nginx serves static files efficiently in production
|
||||||
|
- Multi-stage Docker builds reduce image size
|
||||||
|
- Playwright tests run in headless mode for faster execution
|
||||||
|
- Lucide-react icons use SVG format (no font download)
|
||||||
|
- React Router uses client-side navigation (no page reloads)
|
||||||
|
|
||||||
|
### Security Notes
|
||||||
|
- No sensitive data in client-side code
|
||||||
|
- API credentials should use backend proxy (not direct fetch)
|
||||||
|
- CORS must be configured on backend to accept frontend origin
|
||||||
|
- CSRF protection TBD for future milestones
|
||||||
|
- Playwright test artifacts (.vscode, traces) excluded from git
|
||||||
|
|
||||||
|
### Known Issues / Limitations
|
||||||
|
- No authentication flow implemented yet
|
||||||
|
- Static file serving requires nginx restart on rebuild
|
||||||
|
- Vite HMR doesn't work in Docker without hot-reload support
|
||||||
|
- TypeScript path aliases not configured (using relative imports)
|
||||||
|
- Playwright E2E tests may fail when backend service not available
|
||||||
|
- React Router state preservation not implemented
|
||||||
|
|
||||||
|
### Success Metrics
|
||||||
|
- `npm run dev` starts within 30 seconds
|
||||||
|
- `npm run build` produces <10MB production bundle
|
||||||
|
- TypeScript compilation completes under 5 minutes
|
||||||
|
- Docker frontend image size <200MB
|
||||||
|
- All ESLint rules pass with zero warnings in critical code
|
||||||
|
- Browser console has no errors on page load
|
||||||
|
- Unit tests achieve >=50% coverage on components
|
||||||
|
- E2E tests complete in under 1 minute for core flows
|
||||||
|
- Playwright traces and video artifacts excluded from version control
|
||||||
|
- Lucide-react icons render correctly without fallback errors
|
||||||
|
- React Router navigation works without full page reloads
|
||||||
Reference in new issue
Block a user