✨ MAJOR FEATURES: • Auto-zoom intelligence với smart bounds fitting • Enhanced 3D GPS markers với pulsing effects • Professional route display với 6-layer rendering • Status-based parking icons với availability indicators • Production-ready build optimizations 🗺️ AUTO-ZOOM FEATURES: • Smart bounds fitting cho GPS + selected parking • Adaptive padding (50px) cho visual balance • Max zoom control (level 16) để tránh quá gần • Dynamic centering khi không có selection 🎨 ENHANCED VISUALS: • 3D GPS marker với multi-layer pulse effects • Advanced parking icons với status colors • Selection highlighting với animation • Dimming system cho non-selected items 🛣️ ROUTE SYSTEM: • OpenRouteService API integration • Multi-layer route rendering (glow, shadow, main, animated) • Real-time distance & duration calculation • Visual route info trong popup 📱 PRODUCTION READY: • SSR safe với dynamic imports • Build errors resolved • Global deployment via Vercel • Optimized performance 🌍 DEPLOYMENT: • Vercel: https://whatever-ctk2auuxr-phong12hexdockworks-projects.vercel.app • Bundle size: 22.8 kB optimized • Global CDN distribution • HTTPS enabled 💾 VERSION CONTROL: • MapView-v2.0.tsx backup created • MAPVIEW_VERSIONS.md documentation • Full version history tracking
419 lines
9.0 KiB
Markdown
419 lines
9.0 KiB
Markdown
# 🚗 Smart Parking Finder - Backend API
|
|
|
|
A robust NestJS backend API for the Smart Parking Finder application, providing parking discovery, route calculation, and real-time availability updates.
|
|
|
|
## 🚀 Features
|
|
|
|
- **Parking Discovery**: Find nearby parking lots using PostGIS spatial queries
|
|
- **Route Calculation**: Integration with Valhalla routing engine for turn-by-turn directions
|
|
- **Real-time Updates**: WebSocket support for live parking availability
|
|
- **Comprehensive API**: RESTful endpoints with OpenAPI/Swagger documentation
|
|
- **Performance Optimized**: Redis caching and database connection pooling
|
|
- **Production Ready**: Docker containerization with health checks
|
|
|
|
## 🛠️ Technology Stack
|
|
|
|
- **Framework**: NestJS with TypeScript
|
|
- **Database**: PostgreSQL 15 + PostGIS 3.3
|
|
- **ORM**: TypeORM with spatial support
|
|
- **Caching**: Redis for performance optimization
|
|
- **Documentation**: Swagger/OpenAPI
|
|
- **Security**: Helmet, CORS, rate limiting
|
|
- **Validation**: Class-validator and class-transformer
|
|
|
|
## 📋 Prerequisites
|
|
|
|
- Node.js 18+ and npm
|
|
- Docker and Docker Compose
|
|
- PostgreSQL with PostGIS extension
|
|
- Redis server
|
|
|
|
## 🔧 Installation
|
|
|
|
### Using Docker (Recommended)
|
|
|
|
```bash
|
|
# Start the entire stack
|
|
docker-compose up -d
|
|
|
|
# View logs
|
|
docker-compose logs -f backend
|
|
```
|
|
|
|
### Manual Setup
|
|
|
|
```bash
|
|
# 1. Install dependencies
|
|
npm install
|
|
|
|
# 2. Set up environment variables
|
|
cp .env.example .env
|
|
|
|
# 3. Start PostgreSQL and Redis
|
|
# Make sure both services are running
|
|
|
|
# 4. Run database migrations
|
|
npm run migration:run
|
|
|
|
# 5. Seed initial data
|
|
npm run seed
|
|
|
|
# 6. Start development server
|
|
npm run start:dev
|
|
```
|
|
|
|
## 🌍 Environment Variables
|
|
|
|
```bash
|
|
# Application
|
|
NODE_ENV=development
|
|
PORT=3001
|
|
CORS_ORIGIN=http://localhost:3000
|
|
|
|
# Database
|
|
DATABASE_URL=postgresql://parking_user:parking_pass@localhost:5432/parking_db
|
|
|
|
# Redis
|
|
REDIS_URL=redis://localhost:6379
|
|
|
|
# External Services
|
|
VALHALLA_URL=http://valhalla:8002
|
|
|
|
# Security
|
|
JWT_SECRET=your-super-secure-jwt-secret
|
|
|
|
# Logging
|
|
LOG_LEVEL=debug
|
|
```
|
|
|
|
## 📚 API Documentation
|
|
|
|
Once the server is running, access the interactive API documentation:
|
|
|
|
- **Swagger UI**: http://localhost:3001/api/docs
|
|
- **OpenAPI JSON**: http://localhost:3001/api/docs-json
|
|
|
|
## 🔗 API Endpoints
|
|
|
|
### Parking Management
|
|
|
|
| Method | Endpoint | Description |
|
|
|--------|----------|-------------|
|
|
| POST | `/api/parking/nearby` | Find nearby parking lots |
|
|
| GET | `/api/parking` | Get all parking lots |
|
|
| GET | `/api/parking/popular` | Get popular parking lots |
|
|
| GET | `/api/parking/:id` | Get parking lot details |
|
|
| PUT | `/api/parking/:id/availability` | Update availability |
|
|
| GET | `/api/parking/:id/history` | Get update history |
|
|
|
|
### Route Calculation
|
|
|
|
| Method | Endpoint | Description |
|
|
|--------|----------|-------------|
|
|
| POST | `/api/routing/calculate` | Calculate route between points |
|
|
| GET | `/api/routing/status` | Check routing service status |
|
|
|
|
### System Health
|
|
|
|
| Method | Endpoint | Description |
|
|
|--------|----------|-------------|
|
|
| GET | `/api/health` | Application health check |
|
|
|
|
## 🧪 Example API Usage
|
|
|
|
### Find Nearby Parking
|
|
|
|
```bash
|
|
curl -X POST http://localhost:3001/api/parking/nearby \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"lat": 1.3521,
|
|
"lng": 103.8198,
|
|
"radius": 4000,
|
|
"maxResults": 10
|
|
}'
|
|
```
|
|
|
|
### Calculate Route
|
|
|
|
```bash
|
|
curl -X POST http://localhost:3001/api/routing/calculate \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"originLat": 1.3521,
|
|
"originLng": 103.8198,
|
|
"destinationLat": 1.3048,
|
|
"destinationLng": 103.8318,
|
|
"costing": "auto"
|
|
}'
|
|
```
|
|
|
|
### Update Parking Availability
|
|
|
|
```bash
|
|
curl -X PUT http://localhost:3001/api/parking/1/availability \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"availableSlots": 45,
|
|
"source": "sensor",
|
|
"confidence": 0.95
|
|
}'
|
|
```
|
|
|
|
## 🗄️ Database Schema
|
|
|
|
### Parking Lots Table
|
|
|
|
```sql
|
|
CREATE TABLE parking_lots (
|
|
id SERIAL PRIMARY KEY,
|
|
name VARCHAR(255) NOT NULL,
|
|
address TEXT NOT NULL,
|
|
location GEOGRAPHY(POINT, 4326) NOT NULL,
|
|
lat DOUBLE PRECISION NOT NULL,
|
|
lng DOUBLE PRECISION NOT NULL,
|
|
hourly_rate DECIMAL(10,2),
|
|
open_time TIME,
|
|
close_time TIME,
|
|
available_slots INTEGER DEFAULT 0,
|
|
total_slots INTEGER NOT NULL,
|
|
amenities JSONB DEFAULT '{}',
|
|
contact_info JSONB DEFAULT '{}',
|
|
is_active BOOLEAN DEFAULT true,
|
|
created_at TIMESTAMP DEFAULT NOW(),
|
|
updated_at TIMESTAMP DEFAULT NOW()
|
|
);
|
|
|
|
-- Spatial index for efficient location queries
|
|
CREATE INDEX idx_parking_lots_location ON parking_lots USING GIST (location);
|
|
```
|
|
|
|
## 🔧 Database Management
|
|
|
|
### Run Migrations
|
|
|
|
```bash
|
|
# Generate new migration
|
|
npm run migration:generate src/database/migrations/AddNewFeature
|
|
|
|
# Run pending migrations
|
|
npm run migration:run
|
|
|
|
# Revert last migration
|
|
npm run migration:revert
|
|
```
|
|
|
|
### Seed Data
|
|
|
|
```bash
|
|
# Run all seeds
|
|
npm run seed
|
|
|
|
# Seed specific data
|
|
npm run seed:parking-lots
|
|
```
|
|
|
|
## 📈 Performance Features
|
|
|
|
### Spatial Queries
|
|
|
|
Optimized PostGIS queries for efficient nearby parking search:
|
|
|
|
```sql
|
|
-- Find parking within 4km radius
|
|
SELECT *, ST_Distance(location::geography, ST_Point($1, $2)::geography) as distance
|
|
FROM parking_lots
|
|
WHERE ST_DWithin(location::geography, ST_Point($1, $2)::geography, 4000)
|
|
ORDER BY distance ASC;
|
|
```
|
|
|
|
### Caching Strategy
|
|
|
|
- **Route Calculations**: Cached for 5 minutes
|
|
- **Parking Data**: Cached for 1 minute
|
|
- **Static Data**: Cached for 1 hour
|
|
|
|
### Connection Pooling
|
|
|
|
```typescript
|
|
// Database configuration
|
|
extra: {
|
|
max: 20, // Maximum connections
|
|
connectionTimeoutMillis: 2000,
|
|
idleTimeoutMillis: 30000,
|
|
}
|
|
```
|
|
|
|
## 🛡️ Security Features
|
|
|
|
- **Rate Limiting**: 100 requests per minute per IP
|
|
- **Input Validation**: Comprehensive DTO validation
|
|
- **SQL Injection Protection**: TypeORM query builder
|
|
- **CORS Configuration**: Configurable origins
|
|
- **Helmet**: Security headers middleware
|
|
|
|
## 📊 Monitoring & Logging
|
|
|
|
### Health Checks
|
|
|
|
```bash
|
|
# Application health
|
|
curl http://localhost:3001/api/health
|
|
|
|
# Database connectivity
|
|
curl http://localhost:3001/api/health/database
|
|
|
|
# External services
|
|
curl http://localhost:3001/api/routing/status
|
|
```
|
|
|
|
### Logging Levels
|
|
|
|
- **Error**: Application errors and exceptions
|
|
- **Warn**: Performance issues and deprecation warnings
|
|
- **Info**: General application flow
|
|
- **Debug**: Detailed execution information
|
|
|
|
## 🧪 Testing
|
|
|
|
```bash
|
|
# Unit tests
|
|
npm run test
|
|
|
|
# Test coverage
|
|
npm run test:cov
|
|
|
|
# End-to-end tests
|
|
npm run test:e2e
|
|
|
|
# Watch mode
|
|
npm run test:watch
|
|
```
|
|
|
|
## 🐳 Docker Configuration
|
|
|
|
### Development
|
|
|
|
```bash
|
|
# Start all services
|
|
docker-compose up -d
|
|
|
|
# View logs
|
|
docker-compose logs -f backend
|
|
|
|
# Execute commands in container
|
|
docker-compose exec backend npm run migration:run
|
|
```
|
|
|
|
### Production
|
|
|
|
```bash
|
|
# Build production image
|
|
docker build -t smart-parking-backend .
|
|
|
|
# Run production container
|
|
docker run -p 3001:3001 smart-parking-backend
|
|
```
|
|
|
|
## 🔍 Troubleshooting
|
|
|
|
### Common Issues
|
|
|
|
1. **Database Connection Failed**
|
|
```bash
|
|
# Check PostgreSQL status
|
|
docker-compose exec postgres pg_isready -U parking_user
|
|
|
|
# View database logs
|
|
docker-compose logs postgres
|
|
```
|
|
|
|
2. **Valhalla Service Unavailable**
|
|
```bash
|
|
# Check Valhalla status
|
|
curl http://localhost:8002/status
|
|
|
|
# Restart Valhalla service
|
|
docker-compose restart valhalla
|
|
```
|
|
|
|
3. **High Memory Usage**
|
|
```bash
|
|
# Monitor Docker stats
|
|
docker stats
|
|
|
|
# Optimize connection pool
|
|
# Reduce max connections in database config
|
|
```
|
|
|
|
### Performance Optimization
|
|
|
|
1. **Database Indexes**
|
|
```sql
|
|
-- Monitor slow queries
|
|
SELECT query, mean_time, calls
|
|
FROM pg_stat_statements
|
|
ORDER BY mean_time DESC;
|
|
|
|
-- Add indexes for frequent queries
|
|
CREATE INDEX idx_parking_lots_hourly_rate ON parking_lots(hourly_rate);
|
|
```
|
|
|
|
2. **Cache Optimization**
|
|
```bash
|
|
# Monitor Redis memory usage
|
|
docker-compose exec redis redis-cli info memory
|
|
|
|
# Clear cache if needed
|
|
docker-compose exec redis redis-cli FLUSHALL
|
|
```
|
|
|
|
## 📝 Development Guidelines
|
|
|
|
### Code Style
|
|
|
|
- Use TypeScript strict mode
|
|
- Follow NestJS conventions
|
|
- Implement proper error handling
|
|
- Add comprehensive API documentation
|
|
- Write unit tests for services
|
|
- Use proper logging levels
|
|
|
|
### Git Workflow
|
|
|
|
```bash
|
|
# Feature branch naming
|
|
git checkout -b feature/parking-search-optimization
|
|
|
|
# Commit message format
|
|
git commit -m "feat(parking): optimize spatial queries with better indexing"
|
|
|
|
# Push and create PR
|
|
git push origin feature/parking-search-optimization
|
|
```
|
|
|
|
## 🚀 Deployment
|
|
|
|
### Production Checklist
|
|
|
|
- [ ] Environment variables configured
|
|
- [ ] Database migrations applied
|
|
- [ ] SSL certificates installed
|
|
- [ ] Monitoring setup
|
|
- [ ] Backup strategy implemented
|
|
- [ ] Load balancer configured
|
|
- [ ] CDN setup for static assets
|
|
|
|
## 📞 Support
|
|
|
|
For technical issues or questions:
|
|
|
|
- **Documentation**: Check the API docs at `/api/docs`
|
|
- **Logs**: Use `docker-compose logs backend`
|
|
- **Health Check**: Monitor `/api/health` endpoint
|
|
- **Performance**: Check database and Redis metrics
|
|
|
|
---
|
|
|
|
Built with ❤️ using NestJS and TypeScript
|