# ๐Ÿš— 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