# News Editor Full-stack application for creating, editing, and publishing news articles. ## Architecture ``` ┌──────────────────────────────────┐ │ Nginx (client) │ │ React SPA + reverse proxy │ │ /api → server, /socket.io → ws │ └────────────────┬─────────────────┘ │ ▼ ┌──────────────────────────────────┐ │ Express Backend │ │ Auth (JWT), News CRUD, │ │ Upload (multer), Scheduler, │ │ Socket.IO (Phase 6) │ └────────────────┬─────────────────┘ │ ▼ ┌──────────────────────────────────┐ │ MongoDB │ │ users, news, notifications │ └──────────────────────────────────┘ ``` ## Tech Stack | Layer | Technology | |-----------|---------------------------------------------| | Backend | Node.js 22, Express, TypeScript, Mongoose | | Auth | JWT (jsonwebtoken), bcrypt (cost 12) | | Real-time | Socket.IO (Phase 6) | | Upload | multer (disk storage, UUID filenames) | | Frontend | React 18, TypeScript, Vite, react-router-dom | | Editor | Markdown (react-markdown, remark-gfm) | | Tests | Vitest, Supertest, mongodb-memory-server | | Deploy | Docker Compose (nginx + node + mongo) | ## Project Structure ``` news-editor/ ├── package.json ← root scripts (dev, test, lint, build) ├── docker-compose.yml ← production stack ├── .env ← docker env vars (JWT_SECRET, PORT) ├── server/ │ ├── Dockerfile ← multi-stage: tsc → node:22-alpine │ ├── src/ │ │ ├── app.ts ← Express app factory │ │ ├── server.ts ← entry point (HTTP + scheduler) │ │ ├── config/ ← env, database │ │ ├── middleware/ ← auth (JWT), error, notFound, upload (multer) │ │ ├── models/ ← User, News (Mongoose) │ │ ├── routes/ ← auth, news, upload, health │ │ ├── services/ ← publicationScheduler │ │ └── utils/ ← ApiError, asyncHandler, jwt │ └── tests/ ← integration tests (Vitest + Supertest) └── client/ ├── Dockerfile ← multi-stage: vite build → nginx:alpine ├── nginx.conf ← SPA + proxy └── src/ ├── api/ ← fetch client (apiFetch, apiUpload) ├── auth/ ← AuthContext (login, register, logout) ├── components/ ← ProtectedRoute ├── pages/ ← Login, Register, Home └── App.tsx ← BrowserRouter + Routes ``` ## Prerequisites - Node.js >= 20 - npm >= 10 - MongoDB (local, Atlas, or Docker) - Docker + Docker Compose (for production deploy) ## Development Setup ### 1. Install dependencies ```bash npm install npm --prefix server install npm --prefix client install ``` ### 2. Configure environment ```bash cp server/.env.example server/.env ``` Edit `server/.env`: ```env NODE_ENV=development PORT=3000 MONGODB_URI=mongodb://localhost:27017/news-editor JWT_SECRET=dev-secret-change-in-production JWT_EXPIRES_IN=7d CLIENT_ORIGIN=http://localhost:5173,http://192.168.50.7:5173 MAX_UPLOAD_SIZE=20971520 SCHEDULER_INTERVAL_MS=20000 ``` ### 3. Run MongoDB (if not already running) ```bash # Option A: Docker docker run -d --name mongo -p 27017:27017 mongo:7 # Option B: Local install mongod --dbpath ~/mongodb-data ``` ### 4. Run ```bash # Both server + client (uses concurrently) npm run dev # Or separately npm --prefix server run dev # http://localhost:3000 npm --prefix client run dev # http://localhost:5173 ``` - Backend: http://localhost:3000 - Frontend: http://localhost:5173 - LAN: http://192.168.50.7:5173 - Health: http://localhost:3000/api/health ## Production (Docker Compose) Полный production-стек одним `docker compose up`. ### Архитектура | Сервис | Образ | Описание | |--------|-------|----------| | `mongo` | mongo:7 | MongoDB с healthcheck | | `server` | multi-stage (node:22-alpine) | Express API + Socket.IO | | `client` | multi-stage (nginx:alpine) | React SPA + reverse proxy | ### Запуск ```bash # 1. Настроить .env (JWT_SECRET обязателен) cp .env.docker .env # Отредактируйте JWT_SECRET # 2. Собрать и запустить docker compose up -d --build # 3. Проверить curl http://localhost:8080/api/health # → {"status":"ok"} ``` Приложение доступно на `http://localhost:8080` (или `http://:8080` для LAN). ### Переменные окружения (.env) | Переменная | По умолчанию | Описание | |------------|-------------|----------| | `JWT_SECRET` | — (обязательна) | Секрет подписи JWT | | `PORT` | `8080` | Внешний порт nginx | | `CLIENT_ORIGIN` | `http://localhost:8080` | CORS origin (через запятую — несколько) | ### Остановка ```bash # Остановить контейнеры docker compose down # Остановить + удалить данные (MongoDB + uploads) docker compose down -v ``` ### Файлы | Файл | Назначение | |------|------------| | `docker-compose.yml` | Оркестрация: mongo + server + client | | `server/Dockerfile` | Multi-stage: tsc build → node:22-alpine | | `client/Dockerfile` | Multi-stage: vite build → nginx:alpine | | `client/nginx.conf` | SPA fallback + proxy /api, /uploads, /socket.io | | `.dockerignore` | Исключения из build context | ## API Endpoints ### Auth | Method | Path | Auth | Description | |--------|----------------------|------|--------------------------------| | POST | `/api/auth/register` | – | Register, returns `{token, user}` | | POST | `/api/auth/login` | – | Login, returns `{token, user}` | | GET | `/api/auth/me` | ✓ | Current user info | ### News (authenticated) | Method | Path | Description | |--------|------------------------|------------------------------------| | GET | `/api/news` | List own news | | GET | `/api/news/:id` | Get one news article | | POST | `/api/news` | Create draft | | PATCH | `/api/news/:id` | Update own article | | DELETE | `/api/news/:id` | Delete own article | | POST | `/api/news/:id/publish`| Publish immediately | | POST | `/api/news/:id/schedule`| Schedule publication (`{scheduledAt}`) | ### Upload | Method | Path | Auth | Description | |--------|---------------|------|------------------------------------------| | POST | `/api/uploads`| ✓ | Upload file (multipart), returns `{file}` | | GET | `/uploads/:filename` | – | Serve uploaded file (static) | **MIME whitelist**: image/jpeg, image/png, image/gif, image/webp, application/pdf, application/msword, .docx ### Health | Method | Path | Description | |--------|----------------|-------------------| | GET | `/api/health` | `{"status":"ok"}` | ## Scheduled Publication The backend runs a poller every 20 seconds (configurable via `SCHEDULER_INTERVAL_MS`) that finds articles with: ```js { status: 'scheduled', scheduledAt: { $lte: now } } ``` and atomically transitions them to `published` via `findOneAndUpdate`. Survives process restarts — no in-memory `setTimeout` per article. ## Upload Files are stored on the filesystem (`UPLOAD_DIR`, default `server/uploads/`). Filenames are UUID-based to prevent collisions. Max size: 20 MB (configurable via `MAX_UPLOAD_SIZE`). ## Error Format All errors follow a consistent shape: ```json { "error": { "code": "VALIDATION_ERROR", "message": "Пароль должен содержать минимум 8 символов" } } ``` ## Testing ```bash npm --prefix server test # Vitest + Supertest + mongodb-memory-server (46 tests) npm test # all tests ``` ## Lint ```bash npm run lint # ESLint (strictTypeChecked + sonarjs) for server + client ``` ## Production Build ```bash npm --prefix client run build # Output: client/dist/ (static files, deployable to any static host) ``` ## Demo Flow 1. Register → Login → see JWT with user `id` 2. Create a draft → add markdown content 3. Upload an image → get URL → insert into article 4. Save draft → see in list 5. Schedule publication for 1–2 min ahead → watch it auto-publish 6. Publish immediately → article is live 7. Delete article