From 34fa29c0fc6eaf16f57e9c70b8867f4c11d27092 Mon Sep 17 00:00:00 2001 From: Suslov-MD Date: Sun, 16 Aug 2026 09:53:18 +0000 Subject: [PATCH] chore: Docker Compose production stack, README overhaul --- .dockerignore | 9 ++ .env.docker | 3 + README.md | 260 +++++++++++++++++++++++++++++++-------------- client/Dockerfile | 11 ++ client/nginx.conf | 34 ++++++ docker-compose.yml | 46 ++++++++ server/Dockerfile | 18 ++++ 7 files changed, 299 insertions(+), 82 deletions(-) create mode 100644 .dockerignore create mode 100644 .env.docker create mode 100644 client/Dockerfile create mode 100644 client/nginx.conf create mode 100644 docker-compose.yml create mode 100644 server/Dockerfile diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..9696a1c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +node_modules +client/node_modules +server/node_modules +server/dist +client/dist +server/uploads +.git +*.log +.env diff --git a/.env.docker b/.env.docker new file mode 100644 index 0000000..a546384 --- /dev/null +++ b/.env.docker @@ -0,0 +1,3 @@ +JWT_SECRET=change-me-in-production +PORT=8080 +CLIENT_ORIGIN=http://localhost:8080 diff --git a/README.md b/README.md index 38361bf..dac2f65 100644 --- a/README.md +++ b/README.md @@ -1,52 +1,82 @@ # News Editor -Full-stack application for creating, editing, and publishing news articles with real-time notifications. +Full-stack application for creating, editing, and publishing news articles. ## Architecture ``` -┌──────────────────────────┐ -│ React Client │ -│ Login/Register, News list, -│ Markdown editor, Preview, -│ Notifications bell -└─────────────┬────────────┘ - │ REST + JWT / Socket.IO - ▼ -┌──────────────────────────┐ -│ Express Backend │ -│ Auth middleware, News CRUD, -│ Upload, Scheduler, -│ Socket.IO notifications -└─────────────┬────────────┘ - │ - ▼ -┌──────────────────────────┐ -│ MongoDB Atlas │ -│ users, news, -│ notifications -└──────────────────────────┘ +┌──────────────────────────────────┐ +│ 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, Express, MongoDB/Mongoose | -| Auth | JWT (jsonwebtoken), bcrypt | -| Real-time| Socket.IO | -| Upload | multer (local storage + express.static) | -| Frontend | React 18, Vite, function components | -| Editor | Markdown (react-markdown, remark-gfm) | -| Tests | Vitest, Supertest, mongodb-memory-server| +| 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 >= 18 -- MongoDB Atlas cluster (or local MongoDB) -- npm +- Node.js >= 20 +- npm >= 10 +- MongoDB (local, Atlas, or Docker) +- Docker + Docker Compose (for production deploy) -## Setup +## Development Setup ### 1. Install dependencies @@ -60,37 +90,103 @@ npm --prefix client install ```bash cp server/.env.example server/.env -cp client/.env.example client/.env ``` Edit `server/.env`: ```env -MONGODB_URI=mongodb+srv://:@.example.net/newsEditor -JWT_SECRET= -CLIENT_ORIGIN=http://localhost:5173 +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 ``` -Edit `client/.env`: +### 3. Run MongoDB (if not already running) -```env -VITE_API_URL=http://localhost:3000 +```bash +# Option A: Docker +docker run -d --name mongo -p 27017:27017 mongo:7 + +# Option B: Local install +mongod --dbpath ~/mongodb-data ``` -### 3. Run +### 4. Run ```bash # Both server + client (uses concurrently) npm run dev # Or separately -npm --prefix server run dev -npm --prefix client run dev +npm --prefix server run dev # http://localhost:3000 +npm --prefix client run dev # http://localhost:5173 ``` - Backend: http://localhost:3000 - Frontend: http://localhost:5173 -- Health check: http://localhost:3000/api/health +- 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 @@ -98,71 +194,75 @@ npm --prefix client run dev | Method | Path | Auth | Description | |--------|----------------------|------|--------------------------------| -| POST | `/api/auth/register` | – | Register, returns `{user, token}` | -| POST | `/api/auth/login` | – | Login, returns `{user, token}` | +| 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 (`?status=&page=&limit=`) | +| 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 (`{publishAt}`) | - -### Public - -| Method | Path | Description | -|--------|-----------------------|--------------------------------------| -| GET | `/api/public/news` | List published articles | -| GET | `/api/public/news/:id`| Get one published article | +| 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) | -### Notifications +**MIME whitelist**: image/jpeg, image/png, image/gif, image/webp, application/pdf, application/msword, .docx -| Method | Path | Auth | Description | -|--------|---------------------------------|------|--------------------------| -| GET | `/api/notifications` | ✓ | List notifications | -| PATCH | `/api/notifications/:id/read` | ✓ | Mark as read | -| POST | `/api/notifications/read-all` | ✓ | Mark all as read | +### Health + +| Method | Path | Description | +|--------|----------------|-------------------| +| GET | `/api/health` | `{"status":"ok"}` | ## Scheduled Publication -The backend runs a poller every 15 seconds that finds articles with: +The backend runs a poller every 20 seconds (configurable via `SCHEDULER_INTERVAL_MS`) that finds articles with: ```js -{ status: "scheduled", publishAt: { $lte: now } } +{ status: 'scheduled', scheduledAt: { $lte: now } } ``` -and atomically transitions them to `published`. This survives process restarts — no in-memory `setTimeout` per article. +and atomically transitions them to `published` via `findOneAndUpdate`. Survives process restarts — no in-memory `setTimeout` per article. -## Real-time Notifications +## Upload -Socket.IO runs on the same HTTP server as Express. The client authenticates with the same JWT via `io(API_URL, { auth: { token } })`. +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`). -Events: `news.created`, `news.updated`, `news.deleted`, `news.scheduled`, `news.published`. +## Error Format -Notifications are persisted to MongoDB so the bell survives page reloads. +All errors follow a consistent shape: + +```json +{ + "error": { + "code": "VALIDATION_ERROR", + "message": "Пароль должен содержать минимум 8 символов" + } +} +``` ## Testing ```bash -npm --prefix server test # Vitest + Supertest + mongodb-memory-server +npm --prefix server test # Vitest + Supertest + mongodb-memory-server (46 tests) npm test # all tests ``` ## Lint ```bash -npm run lint # ESLint for server + client +npm run lint # ESLint (strictTypeChecked + sonarjs) for server + client ``` ## Production Build @@ -172,16 +272,12 @@ npm --prefix client run build # Output: client/dist/ (static files, deployable to any static host) ``` -Backend should be deployed to a long-running Node host (not serverless) because of Socket.IO connections and the scheduler. - ## Demo Flow 1. Register → Login → see JWT with user `id` -2. Create a draft → add markdown (heading, bold, quote, code block) -3. Upload an image → insert into article -4. Upload a PDF → insert link -5. Open Preview → see rendered markdown -6. Save draft → see notification in bell -7. Schedule publication for 1–2 min ahead → watch it auto-publish -8. Create another article → publish immediately → delete it -9. Bell shows all events in real-time +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 diff --git a/client/Dockerfile b/client/Dockerfile new file mode 100644 index 0000000..c0e9f5a --- /dev/null +++ b/client/Dockerfile @@ -0,0 +1,11 @@ +FROM node:22-alpine AS build +WORKDIR /app +COPY client/package*.json ./ +RUN npm ci +COPY client/ ./ +RUN npm run build + +FROM nginx:alpine +COPY client/nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/dist /usr/share/nginx/html +EXPOSE 80 diff --git a/client/nginx.conf b/client/nginx.conf new file mode 100644 index 0000000..2175155 --- /dev/null +++ b/client/nginx.conf @@ -0,0 +1,34 @@ +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + index index.html; + + # SPA fallback + location / { + try_files $uri $uri/ /index.html; + } + + # Proxy /api → server + location /api/ { + proxy_pass http://server:3000; + 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 /uploads → server + location /uploads/ { + proxy_pass http://server:3000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + } + + # Proxy /socket.io → server (WebSocket) + location /socket.io/ { + proxy_pass http://server:3000; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ca37221 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,46 @@ +services: + mongo: + image: mongo:7 + restart: unless-stopped + volumes: + - mongo_data:/data/db + healthcheck: + test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"] + interval: 10s + timeout: 5s + retries: 5 + + server: + build: + context: . + dockerfile: server/Dockerfile + restart: unless-stopped + depends_on: + mongo: + condition: service_healthy + environment: + NODE_ENV: production + PORT: 3000 + MONGODB_URI: mongodb://mongo:27017/news-editor + JWT_SECRET: ${JWT_SECRET:?Set JWT_SECRET in .env} + JWT_EXPIRES_IN: 7d + CLIENT_ORIGIN: ${CLIENT_ORIGIN:-http://localhost:8080} + MAX_UPLOAD_SIZE: 20971520 + SCHEDULER_INTERVAL_MS: 20000 + UPLOAD_DIR: /app/uploads + volumes: + - uploads_data:/app/uploads + + client: + build: + context: . + dockerfile: client/Dockerfile + restart: unless-stopped + depends_on: + - server + ports: + - "${PORT:-8080}:80" + +volumes: + mongo_data: + uploads_data: diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..b9d2bf6 --- /dev/null +++ b/server/Dockerfile @@ -0,0 +1,18 @@ +# Stage 1: Build +FROM node:22-alpine AS build +WORKDIR /app +COPY server/package*.json ./ +RUN npm ci +COPY server/ ./ +RUN npm run build + +# Stage 2: Production +FROM node:22-alpine +WORKDIR /app +ENV NODE_ENV=production +COPY server/package*.json ./ +RUN npm ci --omit=dev +COPY --from=build /app/dist ./dist +COPY --from=build /app/package.json ./ +EXPOSE 3000 +CMD ["node", "dist/src/server.js"]