chore: Docker Compose production stack, README overhaul
This commit is contained in:
@@ -0,0 +1,9 @@
|
|||||||
|
node_modules
|
||||||
|
client/node_modules
|
||||||
|
server/node_modules
|
||||||
|
server/dist
|
||||||
|
client/dist
|
||||||
|
server/uploads
|
||||||
|
.git
|
||||||
|
*.log
|
||||||
|
.env
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
JWT_SECRET=change-me-in-production
|
||||||
|
PORT=8080
|
||||||
|
CLIENT_ORIGIN=http://localhost:8080
|
||||||
@@ -1,52 +1,82 @@
|
|||||||
# News Editor
|
# 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
|
## Architecture
|
||||||
|
|
||||||
```
|
```
|
||||||
┌──────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ React Client │
|
│ Nginx (client) │
|
||||||
│ Login/Register, News list,
|
│ React SPA + reverse proxy │
|
||||||
│ Markdown editor, Preview,
|
│ /api → server, /socket.io → ws │
|
||||||
│ Notifications bell
|
└────────────────┬─────────────────┘
|
||||||
└─────────────┬────────────┘
|
|
||||||
│ REST + JWT / Socket.IO
|
|
||||||
▼
|
|
||||||
┌──────────────────────────┐
|
|
||||||
│ Express Backend │
|
|
||||||
│ Auth middleware, News CRUD,
|
|
||||||
│ Upload, Scheduler,
|
|
||||||
│ Socket.IO notifications
|
|
||||||
└─────────────┬────────────┘
|
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌──────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ MongoDB Atlas │
|
│ Express Backend │
|
||||||
│ users, news,
|
│ Auth (JWT), News CRUD, │
|
||||||
│ notifications
|
│ Upload (multer), Scheduler, │
|
||||||
└──────────────────────────┘
|
│ Socket.IO (Phase 6) │
|
||||||
|
└────────────────┬─────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────┐
|
||||||
|
│ MongoDB │
|
||||||
|
│ users, news, notifications │
|
||||||
|
└──────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
## Tech Stack
|
## Tech Stack
|
||||||
|
|
||||||
| Layer | Technology |
|
| Layer | Technology |
|
||||||
|----------|-----------------------------------------|
|
|-----------|---------------------------------------------|
|
||||||
| Backend | Node.js, Express, MongoDB/Mongoose |
|
| Backend | Node.js 22, Express, TypeScript, Mongoose |
|
||||||
| Auth | JWT (jsonwebtoken), bcrypt |
|
| Auth | JWT (jsonwebtoken), bcrypt (cost 12) |
|
||||||
| Real-time| Socket.IO |
|
| Real-time | Socket.IO (Phase 6) |
|
||||||
| Upload | multer (local storage + express.static) |
|
| Upload | multer (disk storage, UUID filenames) |
|
||||||
| Frontend | React 18, Vite, function components |
|
| Frontend | React 18, TypeScript, Vite, react-router-dom |
|
||||||
| Editor | Markdown (react-markdown, remark-gfm) |
|
| Editor | Markdown (react-markdown, remark-gfm) |
|
||||||
| Tests | Vitest, Supertest, mongodb-memory-server|
|
| 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
|
## Prerequisites
|
||||||
|
|
||||||
- Node.js >= 18
|
- Node.js >= 20
|
||||||
- MongoDB Atlas cluster (or local MongoDB)
|
- npm >= 10
|
||||||
- npm
|
- MongoDB (local, Atlas, or Docker)
|
||||||
|
- Docker + Docker Compose (for production deploy)
|
||||||
|
|
||||||
## Setup
|
## Development Setup
|
||||||
|
|
||||||
### 1. Install dependencies
|
### 1. Install dependencies
|
||||||
|
|
||||||
@@ -60,37 +90,103 @@ npm --prefix client install
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp server/.env.example server/.env
|
cp server/.env.example server/.env
|
||||||
cp client/.env.example client/.env
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Edit `server/.env`:
|
Edit `server/.env`:
|
||||||
|
|
||||||
```env
|
```env
|
||||||
MONGODB_URI=mongodb+srv://<user>:<pass>@<cluster>.example.net/newsEditor
|
NODE_ENV=development
|
||||||
JWT_SECRET=<generate-a-long-random-string>
|
PORT=3000
|
||||||
CLIENT_ORIGIN=http://localhost:5173
|
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
|
```bash
|
||||||
VITE_API_URL=http://localhost:3000
|
# 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
|
```bash
|
||||||
# Both server + client (uses concurrently)
|
# Both server + client (uses concurrently)
|
||||||
npm run dev
|
npm run dev
|
||||||
|
|
||||||
# Or separately
|
# Or separately
|
||||||
npm --prefix server run dev
|
npm --prefix server run dev # http://localhost:3000
|
||||||
npm --prefix client run dev
|
npm --prefix client run dev # http://localhost:5173
|
||||||
```
|
```
|
||||||
|
|
||||||
- Backend: http://localhost:3000
|
- Backend: http://localhost:3000
|
||||||
- Frontend: http://localhost:5173
|
- 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://<IP>: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
|
## API Endpoints
|
||||||
|
|
||||||
@@ -98,71 +194,75 @@ npm --prefix client run dev
|
|||||||
|
|
||||||
| Method | Path | Auth | Description |
|
| Method | Path | Auth | Description |
|
||||||
|--------|----------------------|------|--------------------------------|
|
|--------|----------------------|------|--------------------------------|
|
||||||
| POST | `/api/auth/register` | – | Register, returns `{user, token}` |
|
| POST | `/api/auth/register` | – | Register, returns `{token, user}` |
|
||||||
| POST | `/api/auth/login` | – | Login, returns `{user, token}` |
|
| POST | `/api/auth/login` | – | Login, returns `{token, user}` |
|
||||||
|
| GET | `/api/auth/me` | ✓ | Current user info |
|
||||||
|
|
||||||
### News (authenticated)
|
### News (authenticated)
|
||||||
|
|
||||||
| Method | Path | Description |
|
| 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 |
|
| GET | `/api/news/:id` | Get one news article |
|
||||||
| POST | `/api/news` | Create draft |
|
| POST | `/api/news` | Create draft |
|
||||||
| PATCH | `/api/news/:id` | Update own article |
|
| PATCH | `/api/news/:id` | Update own article |
|
||||||
| DELETE | `/api/news/:id` | Delete own article |
|
| DELETE | `/api/news/:id` | Delete own article |
|
||||||
| POST | `/api/news/:id/publish`| Publish immediately |
|
| POST | `/api/news/:id/publish`| Publish immediately |
|
||||||
| POST | `/api/news/:id/schedule`| Schedule publication (`{publishAt}`) |
|
| POST | `/api/news/:id/schedule`| Schedule publication (`{scheduledAt}`) |
|
||||||
|
|
||||||
### Public
|
|
||||||
|
|
||||||
| Method | Path | Description |
|
|
||||||
|--------|-----------------------|--------------------------------------|
|
|
||||||
| GET | `/api/public/news` | List published articles |
|
|
||||||
| GET | `/api/public/news/:id`| Get one published article |
|
|
||||||
|
|
||||||
### Upload
|
### Upload
|
||||||
|
|
||||||
| Method | Path | Auth | Description |
|
| Method | Path | Auth | Description |
|
||||||
|--------|---------------|------|------------------------------------------|
|
|--------|---------------|------|------------------------------------------|
|
||||||
| POST | `/api/uploads`| ✓ | Upload file (multipart), returns `{file}` |
|
| 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 |
|
### Health
|
||||||
|--------|---------------------------------|------|--------------------------|
|
|
||||||
| GET | `/api/notifications` | ✓ | List notifications |
|
| Method | Path | Description |
|
||||||
| PATCH | `/api/notifications/:id/read` | ✓ | Mark as read |
|
|--------|----------------|-------------------|
|
||||||
| POST | `/api/notifications/read-all` | ✓ | Mark all as read |
|
| GET | `/api/health` | `{"status":"ok"}` |
|
||||||
|
|
||||||
## Scheduled Publication
|
## 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
|
```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
|
## Testing
|
||||||
|
|
||||||
```bash
|
```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
|
npm test # all tests
|
||||||
```
|
```
|
||||||
|
|
||||||
## Lint
|
## Lint
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run lint # ESLint for server + client
|
npm run lint # ESLint (strictTypeChecked + sonarjs) for server + client
|
||||||
```
|
```
|
||||||
|
|
||||||
## Production Build
|
## Production Build
|
||||||
@@ -172,16 +272,12 @@ npm --prefix client run build
|
|||||||
# Output: client/dist/ (static files, deployable to any static host)
|
# 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
|
## Demo Flow
|
||||||
|
|
||||||
1. Register → Login → see JWT with user `id`
|
1. Register → Login → see JWT with user `id`
|
||||||
2. Create a draft → add markdown (heading, bold, quote, code block)
|
2. Create a draft → add markdown content
|
||||||
3. Upload an image → insert into article
|
3. Upload an image → get URL → insert into article
|
||||||
4. Upload a PDF → insert link
|
4. Save draft → see in list
|
||||||
5. Open Preview → see rendered markdown
|
5. Schedule publication for 1–2 min ahead → watch it auto-publish
|
||||||
6. Save draft → see notification in bell
|
6. Publish immediately → article is live
|
||||||
7. Schedule publication for 1–2 min ahead → watch it auto-publish
|
7. Delete article
|
||||||
8. Create another article → publish immediately → delete it
|
|
||||||
9. Bell shows all events in real-time
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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:
|
||||||
@@ -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"]
|
||||||
Reference in New Issue
Block a user