Develop #2

Merged
daniel merged 3 commits from develop into main 2026-10-30 13:10:20 +00:00
33 changed files with 1884 additions and 1 deletions

No files matched your search

+2 -1
View File
@@ -9,7 +9,8 @@
| Milestone | Description | Status |
| --------- | ------------------------- | -------- |
| M1 | Git project setup | Done |
| M2+ | News application features | Planned |
| M2 | Backend setup (FastAPI) | Done |
| M3+ | News application features | Planned |
See [milestones/](milestones/) for milestone prompts and progress tracking.
+22
View File
@@ -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
+7
View File
@@ -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
+30
View File
@@ -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/
+19
View File
@@ -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"]
+199
View File
@@ -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.
+1
View File
@@ -0,0 +1 @@
"""API package (versioned route groups)."""
+23
View File
@@ -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)
+45
View File
@@ -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()
+5
View File
@@ -0,0 +1,5 @@
"""Core package (application factory and global error handling)."""
from core.app import create_app
__all__ = ["create_app"]
+111
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
"""Database package (engine, session management)."""
+64
View File
@@ -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()
+15
View File
@@ -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)
+8
View File
@@ -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"]
+40
View File
@@ -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}>"
+24
View File
@@ -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}>"
+7
View File
@@ -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."""
+41
View File
@@ -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}>"
+9
View File
@@ -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
+19
View File
@@ -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
+24
View File
@@ -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",
]
+44
View File
@@ -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
+38
View File
@@ -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
+51
View File
@@ -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)
+29
View File
@@ -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
+78
View File
@@ -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()
+29
View File
@@ -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
+137
View File
@@ -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()
+23
View File
@@ -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
+15
View File
@@ -0,0 +1,15 @@
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
+305
View File
@@ -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
+419
View File
@@ -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