418 lines
13 KiB
Markdown
418 lines
13 KiB
Markdown
# Changelog - Backend Node.js
|
|
|
|
Tracciamento modifiche specifiche del backend.
|
|
|
|
---
|
|
|
|
## ✅ Completato
|
|
|
|
### Setup Iniziale
|
|
- [x] Inizializzazione progetto Node.js con npm
|
|
- [x] Installazione dipendenze: Express, Sequelize, Mongoose, CORS, pg
|
|
- [x] Configurazione server Express (server.js)
|
|
- [x] Setup doppia connessione database (PostgreSQL + MongoDB)
|
|
|
|
### Database PostgreSQL
|
|
|
|
#### Modelli Sequelize
|
|
- [x] **User Model** (`models/user.model.js`)
|
|
- Campi: id, name, email, avatarUrl, score
|
|
- Validazioni email unique
|
|
- Relazioni: belongsToMany Groups, hasMany FriendRequests
|
|
|
|
- [x] **Group Model** (`models/group.model.js`)
|
|
- Campi: id, name
|
|
- Relazioni: belongsToMany Users (many-to-many)
|
|
|
|
- [x] **Friendship Model** (`models/friendship.model.js`)
|
|
- Campi: id, user1Id, user2Id
|
|
- Vincolo: user1Id < user2Id (evita duplicati)
|
|
- Hook beforeValidate per garantire ordine corretto
|
|
|
|
- [x] **FriendRequest Model** (`models/friendRequest.model.js`)
|
|
- Campi: id, fromUserId, toUserId, status, createdAt, updatedAt
|
|
- Stati: PENDING, ACCEPTED, REJECTED
|
|
- Timestamps automatici
|
|
|
|
- [x] **Associations** (`models/associations.js`)
|
|
- User ↔ Group (many-to-many via UserGroups)
|
|
- User → FriendRequest (fromUser, toUser)
|
|
- Friendship → User (user1, user2)
|
|
|
|
#### Schema SQL
|
|
- [x] Script di inizializzazione (`init.sql`)
|
|
- [x] Definizione tabelle con constraint e foreign keys
|
|
- [x] Indici per performance su ricerche frequenti
|
|
- [x] Check constraints per data integrity
|
|
|
|
### Database MongoDB
|
|
|
|
- [x] **Bet Model** (`models/bet.model.js`)
|
|
- Schema: title, description, stake, participants[], status, startDate, endDate, isPublic, groupId, winner
|
|
- Partecipanti con ruolo (PARTICIPANT/OBSERVER)
|
|
- Stati: ACTIVE, AWAITING_VALIDATION, COMPLETED
|
|
- Timestamp automatici (createdAt, updatedAt)
|
|
|
|
### API Routes
|
|
|
|
#### Initial Data Route (`routes/initial-data.routes.js`)
|
|
- [x] `GET /api/initial-data` - Carica dati iniziali per l'app
|
|
- Utente corrente (hardcoded userId=1 per ora)
|
|
- Lista amici con info complete
|
|
- Gruppi dell'utente con membri
|
|
- Scommesse dell'utente (tutte, attive, passate)
|
|
|
|
#### Users Routes (`routes/users.routes.js`)
|
|
- [x] `GET /api/users` - Lista tutti gli utenti
|
|
- [x] `GET /api/users/:id` - Dettaglio utente singolo
|
|
|
|
#### Groups Routes (`routes/groups.routes.js`)
|
|
- [x] `GET /api/groups` - Lista tutti i gruppi
|
|
- [x] `GET /api/groups/:id` - Dettaglio gruppo con membri
|
|
- [x] `POST /api/groups` - Crea nuovo gruppo
|
|
- [x] `PUT /api/groups/:id` - Aggiorna gruppo
|
|
- [x] `DELETE /api/groups/:id` - Elimina gruppo
|
|
- [x] `POST /api/groups/:id/members` - Aggiungi membro al gruppo
|
|
- [x] `DELETE /api/groups/:id/members/:userId` - Rimuovi membro
|
|
|
|
#### Bets Routes (`routes/bets.routes.js`)
|
|
- [x] `GET /api/bets` - Lista tutte le scommesse
|
|
- [x] `GET /api/bets/:id` - Dettaglio scommessa
|
|
- [x] `POST /api/bets` - Crea nuova scommessa
|
|
- [x] `PUT /api/bets/:id` - Aggiorna scommessa
|
|
- [x] `DELETE /api/bets/:id` - Elimina scommessa
|
|
- [x] `GET /api/bets/by-time` - Filtra scommesse per periodo (today, week, month)
|
|
- [x] `GET /api/bets/by-group/:groupId` - Scommesse per gruppo specifico
|
|
|
|
#### Friends Routes (`routes/friends.routes.js`)
|
|
- [x] `GET /api/friends/:userId` - Lista amici di un utente
|
|
- [x] `GET /api/friends/requests/:userId` - Richieste di amicizia pending
|
|
- [x] `POST /api/friends/requests` - Invia richiesta di amicizia
|
|
- [x] `PATCH /api/friends/requests/:requestId` - Accetta/rifiuta richiesta
|
|
|
|
#### API Router (`routes/api.js`)
|
|
- [x] Router factory che accetta istanza Sequelize
|
|
- [x] Composizione di tutti i sub-router
|
|
|
|
### Utilities
|
|
- [x] **Seed Script** (`seed.js`)
|
|
- Popola PostgreSQL con 6 utenti di test
|
|
- Crea 3 amicizie e 2 richieste pending
|
|
- Crea 2 gruppi con membri
|
|
- Popola MongoDB con 5 scommesse di esempio
|
|
- Skip automatico se database già popolato
|
|
|
|
- [x] **Populate Bets** (`utils/populateBets.js`)
|
|
- Utility per popolare scommesse (se necessario)
|
|
|
|
### Configurazione
|
|
- [x] Sync automatico con `{ force: true }` in development
|
|
- [x] Seed automatico al primo avvio
|
|
- [x] CORS abilitato per frontend
|
|
- [x] JSON body parser
|
|
- [x] Gestione errori connessione database
|
|
|
|
---
|
|
|
|
## 📋 Da Fare
|
|
|
|
### Autenticazione & Autorizzazione
|
|
- [ ] Implementare JWT authentication
|
|
- [ ] Middleware di protezione route
|
|
- [ ] Login/Register endpoints
|
|
- [ ] Password hashing (bcrypt)
|
|
- [ ] Refresh token mechanism
|
|
- [ ] OAuth2 integration (Google, Facebook)
|
|
- [ ] Gestione sessioni
|
|
|
|
### Validazione & Sicurezza
|
|
- [ ] Validation middleware con Joi/express-validator
|
|
- [ ] Sanitizzazione input utente
|
|
- [ ] Rate limiting per API
|
|
- [ ] CORS configuration più restrittiva per production
|
|
- [ ] Helmet.js per security headers
|
|
- [ ] SQL injection prevention (già parzialmente coperto da Sequelize)
|
|
- [ ] XSS protection
|
|
|
|
### Funzionalità Scommesse
|
|
- [ ] Endpoint per dichiarare vincitore
|
|
- [ ] Sistema di votazione vincitori (per scommesse tra amici)
|
|
- [ ] Logica di calcolo punteggi utenti
|
|
- [ ] Notifiche per eventi scommessa
|
|
- [ ] Endpoint statistiche utente
|
|
- Win rate
|
|
- Streak attuali
|
|
- Scommesse vinte/perse
|
|
- Classifica generale
|
|
- [ ] Filtri avanzati per ricerca scommesse
|
|
- [ ] Paginazione scommesse
|
|
- [ ] Cronologia completa scommesse
|
|
|
|
### Funzionalità Sociali
|
|
- [ ] Endpoint per chat/commenti nelle scommesse
|
|
- [ ] WebSocket/SSE per notifiche real-time
|
|
- [ ] Sistema di notifiche persistenti
|
|
- [ ] Feed attività (chi ha creato cosa, chi ha vinto, ecc.)
|
|
- [ ] Richieste di amicizia: suggerimenti basati su amici in comune
|
|
- [ ] Blocco utenti
|
|
- [ ] Report/segnalazioni
|
|
|
|
### Funzionalità Gruppi
|
|
- [ ] Ruoli nei gruppi (admin, membro)
|
|
- [ ] Inviti al gruppo
|
|
- [ ] Statistiche gruppo
|
|
- [ ] Impostazioni privacy gruppo
|
|
|
|
### File & Media
|
|
- [ ] Upload avatar utente
|
|
- [ ] Upload immagini nelle scommesse
|
|
- [ ] Integrazione storage (S3, Cloudinary)
|
|
- [ ] Resize/compression immagini
|
|
|
|
### Performance & Optimization
|
|
- [ ] Caching con Redis
|
|
- Cache lista amici
|
|
- Cache gruppi utente
|
|
- Cache scommesse popolari
|
|
- [ ] Query optimization
|
|
- [ ] Indici database aggiuntivi dove necessario
|
|
- [ ] Paginazione su tutti gli endpoint liste
|
|
- [ ] Response compression (gzip)
|
|
- [ ] Database connection pooling optimization
|
|
|
|
### Testing
|
|
- [ ] Unit test per modelli
|
|
- [ ] Integration test per API endpoints
|
|
- [ ] Test copertura almeno 80%
|
|
- [ ] Mock database per test
|
|
- [ ] Setup test runner (Jest/Mocha)
|
|
|
|
### DevOps
|
|
- [ ] Logging strutturato (Winston/Pino)
|
|
- [ ] Health check endpoint (`/health`)
|
|
- [ ] Metrics endpoint (`/metrics`)
|
|
- [ ] Error tracking (Sentry)
|
|
- [ ] Environment variables validation
|
|
- [ ] Graceful shutdown
|
|
- [ ] Dockerfile per production
|
|
- [ ] Docker multi-stage build
|
|
|
|
### Database
|
|
- [ ] Migration system (invece di sync force)
|
|
- [ ] Backup automatici
|
|
- [ ] Soft delete per entità critiche
|
|
- [ ] Audit log per modifiche importanti
|
|
- [ ] Database indexing strategy review
|
|
|
|
### API Documentation
|
|
- [ ] Swagger/OpenAPI specification
|
|
- [ ] Endpoint documentation con esempi
|
|
- [ ] Postman collection
|
|
- [ ] API versioning strategy
|
|
|
|
### Monitoring
|
|
- [ ] Application Performance Monitoring (APM)
|
|
- [ ] Database query monitoring
|
|
- [ ] Error rate alerts
|
|
- [ ] Response time monitoring
|
|
|
|
---
|
|
|
|
## 🐛 Bug Conosciuti
|
|
- Nessuno al momento
|
|
|
|
---
|
|
|
|
## 🔧 Miglioramenti Tecnici Completati (v1.1.0 - 2024)
|
|
|
|
### Refactoring Architetturale
|
|
- [x] **Separazione logica business dai controller (service layer)**
|
|
- Creati 5 services: users, groups, friends, bets, data-stitching
|
|
- Business logic completamente spostata dai controller ai services
|
|
- `services/` directory con pattern consistente
|
|
|
|
- [x] **Dependency Injection Container**
|
|
- Implementato Awilix per DI
|
|
- Container setup in `di/container.js`
|
|
- Registrazione automatica di repositories, services, controllers
|
|
- Lifetime management: singleton per database, scoped per services
|
|
|
|
- [x] **Request/Response DTOs**
|
|
- Validation schemas con Joi
|
|
- 4 schemas: group, bet, user, friendRequest
|
|
- Middleware validation in `middleware/validation.js`
|
|
- Input sanitization automatico
|
|
|
|
- [x] **Standardizzazione formato risposte API**
|
|
- ResponseHandler class in `shared/response.handler.js`
|
|
- Formato consistente per successo e errori
|
|
- Timestamp automatico in ogni risposta
|
|
- Metodi: success, created, error, badRequest, notFound, etc.
|
|
|
|
- [x] **Error handling centralizzato**
|
|
- Custom errors: ValidationError, NotFoundError, ConflictError, etc.
|
|
- Global error handler middleware
|
|
- Gestione errori Sequelize e Mongoose
|
|
- Stack trace solo in development
|
|
|
|
- [x] **Constants file per magic numbers/strings**
|
|
- `config/constants.js`: HTTP_STATUS, BET_STATUS, FRIEND_REQUEST_STATUS, etc.
|
|
- `config/database.js`: configurazione database centralizzata
|
|
- `config/index.js`: export centralizzato
|
|
|
|
- [x] **Code linting (ESLint) e formatting (Prettier)**
|
|
- ESLint configurato con airbnb-base
|
|
- Prettier per code formatting
|
|
- Scripts npm: lint, lint:fix, format
|
|
- .eslintrc.json e .prettierrc
|
|
|
|
- [ ] **Type checking con TypeScript** - SKIPPED (troppo invasivo per questa fase)
|
|
|
|
### Nuova Struttura Architetturale
|
|
|
|
```
|
|
Routes (thin) → Validation → Controllers → Services → Repositories → Database
|
|
↓ ↓ ↓
|
|
ResponseHandler Business Logic DB Access
|
|
```
|
|
|
|
**Directory create:**
|
|
- `config/` - Configurazione centralizzata (3 files)
|
|
- `shared/errors/` - Custom errors (2 files)
|
|
- `shared/validators/schemas/` - Joi schemas (4 files)
|
|
- `shared/response.handler.js` - Standardized responses
|
|
- `middleware/` - errorHandler, validation, auth.mock (3 files)
|
|
- `di/` - Dependency injection container (1 file)
|
|
- `repositories/postgres/` - PostgreSQL repositories (4 files)
|
|
- `repositories/mongo/` - MongoDB repositories (1 file)
|
|
- `services/` - Business logic services (5 files)
|
|
- `controllers/` - Thin controllers (5 files)
|
|
- `routes/v1/` - API v1 routes (6 files)
|
|
- `routes/health.routes.js` - Health check endpoint
|
|
|
|
**File modificati:**
|
|
- `server.js` - Refactored per integrare DI container e nuova architettura
|
|
- `package.json` - Aggiunte dipendenze e scripts
|
|
|
|
### API Versioning
|
|
|
|
- **`/api/v1/*`** - Nuova API con architettura refactored
|
|
- Formato risposte standardizzato
|
|
- Validazione automatica input
|
|
- Error handling consistente
|
|
|
|
- **`/api/legacy/*`** - API legacy (backward compatibility)
|
|
- Routes originali spostate qui
|
|
- Mantiene formato originale
|
|
- Per garantire compatibilità durante migrazione
|
|
|
|
- **`/health`** - Health check endpoint
|
|
- Verifica connessioni PostgreSQL e MongoDB
|
|
- Status: healthy/unhealthy
|
|
|
|
### Endpoints API v1
|
|
|
|
#### Groups (`/api/v1/groups`)
|
|
- `GET /` - Lista tutti i gruppi
|
|
- `GET /:id` - Dettaglio gruppo con membri
|
|
- `POST /` - Crea gruppo (validato con Joi)
|
|
- `PUT /:id` - Aggiorna gruppo (validato)
|
|
- `DELETE /:id` - Elimina gruppo
|
|
- `PUT /:id/members` - Aggiungi membri (validato)
|
|
- `DELETE /:id/members/:userId` - Rimuovi membro
|
|
|
|
#### Bets (`/api/v1/bets`)
|
|
- `GET /` - Lista tutte le scommesse
|
|
- `GET /:id` - Dettaglio scommessa
|
|
- `POST /` - Crea scommessa (validato con Joi)
|
|
- `PUT /:id` - Aggiorna scommessa (validato)
|
|
- `DELETE /:id` - Elimina scommessa
|
|
|
|
#### Friend Requests (`/api/v1/friend-requests`)
|
|
- `GET /` - Lista amici dell'utente corrente
|
|
- `GET /pending` - Richieste pending
|
|
- `POST /` - Invia richiesta (validato con Joi)
|
|
- `POST /:id/accept` - Accetta richiesta
|
|
- `DELETE /:id` - Rifiuta/cancella richiesta
|
|
|
|
#### Users (`/api/v1/users`)
|
|
- `PUT /current` - Aggiorna profilo utente corrente (validato)
|
|
|
|
#### Initial Data (`/api/v1/initial-data`)
|
|
- `GET /` - Carica dati iniziali (currentUser, users, friends, groups, bets)
|
|
|
|
#### Health Check (`/health`)
|
|
- `GET /` - Status database (PostgreSQL, MongoDB)
|
|
|
|
### Formato Risposte Standardizzato
|
|
|
|
**Successo:**
|
|
```json
|
|
{
|
|
"success": true,
|
|
"message": "Operation successful",
|
|
"data": { ... },
|
|
"timestamp": "2024-01-01T00:00:00.000Z"
|
|
}
|
|
```
|
|
|
|
**Errore:**
|
|
```json
|
|
{
|
|
"success": false,
|
|
"message": "Error message",
|
|
"errors": [{"field": "name", "message": "Required"}],
|
|
"timestamp": "2024-01-01T00:00:00.000Z"
|
|
}
|
|
```
|
|
|
|
### Benefici dell'Architettura
|
|
|
|
- ✅ **Separation of Concerns**: Ogni layer ha responsabilità ben definite
|
|
- ✅ **Testability**: Services e repositories facilmente testabili
|
|
- ✅ **Maintainability**: Business logic centralizzata
|
|
- ✅ **Consistency**: Formato risposte e errori standardizzati
|
|
- ✅ **Scalability**: Facile aggiungere nuove feature
|
|
- ✅ **Type Safety**: Validation layer previene dati inconsistenti
|
|
- ✅ **Backward Compatibility**: Routes legacy funzionano ancora
|
|
|
|
---
|
|
|
|
## Note Tecniche
|
|
|
|
### Dipendenze Principali
|
|
- **express**: ^4.19.2
|
|
- **sequelize**: ^6.37.3 (PostgreSQL ORM)
|
|
- **mongoose**: ^8.4.0 (MongoDB ODM)
|
|
- **pg**: ^8.11.5 (PostgreSQL driver)
|
|
- **cors**: ^2.8.5
|
|
- **awilix**: ^10.0.2 (Dependency Injection)
|
|
- **joi**: ^17.12.1 (Validation)
|
|
|
|
### Dev Dependencies
|
|
- **eslint**: ^8.56.0
|
|
- **prettier**: ^3.2.4
|
|
- **eslint-config-airbnb-base**: ^15.0.0
|
|
- **eslint-config-prettier**: ^9.1.0
|
|
|
|
### Variabili Ambiente Richieste
|
|
```bash
|
|
PORT=3000
|
|
NODE_ENV=development
|
|
MONGO_URI=mongodb://root:root@servovio@localhost:27017/amici-scommesse
|
|
POSTGRES_URI=postgres://admin:admin@localhost:5432/amici_scommesse
|
|
```
|
|
|
|
### Porte
|
|
- Server: `3000`
|
|
- PostgreSQL: `5432`
|
|
- MongoDB: `27017`
|
|
|
|
### Scripts npm
|
|
```bash
|
|
npm start # Avvia server
|
|
npm run lint # Check linting
|
|
npm run lint:fix # Fix linting automaticamente
|
|
npm run format # Format codice con Prettier
|
|
```
|