@@ -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
└─────────────┬────────────┘
┌────────────────────────────────── ┐
│ Nginx (client) │
│ React SPA + reverse proxy │
│ /api → server, /socket.io → ws │
└────────────────┬─────────────────┘
│
▼
┌──────────────────────────┐
│ MongoDB Atlas │
│ users , n ews,
│ notifications
└──────────────────────────┘
┌────────────────────────────────── ┐
│ Express Backend │
│ Auth (JWT) , N ews 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 |
|-----------|---- -----------------------------------------|
| 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|
| 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://<user>:<pass>@<cluster>.example.net/newsEditor
JWT_SECRET = <generate-a-long-random-string>
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://<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
@@ -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 (`{publish At}` ) |
### 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 (`{scheduled At}` ) |
### 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 notifica tions |
| PATCH | `/api/notifications/:id/read` | ✓ | Mark as read |
| POST | `/api/notifications/read-all ` | ✓ | Mark all as read |
### Health
| Method | Path | Descrip tion |
|--------|----------------|------------------- |
| 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 s urvives process restarts — no in-memory `setTimeout` per article.
and atomically transitions them to `published` via `findOneAndUpdate` . S urvives 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