UNPKG

@sehirapp/core-microservice

Version:

Modern mikroservis core paketi - MongoDB 6.7, Express API, Mongoose, PM2 cluster desteği

427 lines (318 loc) 9.96 kB
# Generic Mikroservis Template Core Mikroservis paketi kullanarak hazırlanmış generic mikroservis template'i. Bu template'i kendi mikroservisiniz için başlangıç noktası olarak kullanın. ## 🚀 Özellikler -**Modern Teknoloji Stack**: Node.js v22 + Express + MongoDB + Mongoose -**Core Package Integration**: `core-microservice` paketi ile entegre -**API Key Authentication**: Gateway doğrulaması -**Rate Limiting & Security**: CORS, Helmet, Rate limiting -**PM2 Cluster Support**: Production-ready cluster desteği -**Structured Logging**: Winston ile detaylı logging -**Model & Controller Pattern**: BaseController ile CRUD işlemleri -**MongoDB Atlas Ready**: Cloud database desteği -**Health Checks**: Health monitoring endpoints -**Request Validation**: Express-validator ile input validation ## 🎯 Bu Template'i Nasıl Kullanırım? 1. **Template'i Kopyala**: Bu klasörü kendi mikroservisiniz için kopyalayın 2. **Model'i Değiştir**: `src/models/Item.js`'yi kendi model'inizle değiştirin 3. **Controller'ı Özelleştir**: `src/controllers/ItemController.js`'yi ihtiyacınıza göre güncelleyin 4. **Route'ları Düzenle**: `src/routes/itemRoutes.js`'yi kendi endpoint'lerinizle değiştirin 5. **Environment Variables**: `.env` dosyasında servis adı ve database ayarlarını yapın ## 📁 Proje Yapısı ``` generic-microservice/ ├── src/ │ ├── controllers/ # API Controller'ları │ │ └── ItemController.js # Generic CRUD controller (değiştirin) │ ├── models/ # Mongoose Model'leri │ │ └── Item.js # Generic model (değiştirin) │ ├── routes/ # Route tanımları │ │ └── itemRoutes.js # Generic routes (değiştirin) │ ├── middleware/ # Custom middleware'ler │ │ └── authMiddleware.js # JWT auth örneği │ └── index.js # Ana uygulama dosyası ├── logs/ # PM2 log dosyaları ├── package.json ├── ecosystem.config.js # PM2 konfigürasyonu ├── env.example # Environment variables örneği └── README.md ``` ## 🛠️ Kurulum ### 1. Bağımlılıkları Yükle ```bash npm install ``` ### 2. Environment Variables `env.example` dosyasını `.env` olarak kopyalayın ve değerleri güncelleyin: ```bash cp env.example .env ``` ### 3. MongoDB Konfigürasyonu #### MongoDB Atlas (Önerilen) ```env MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/database_name?retryWrites=true&w=majority ``` #### Lokal MongoDB ```env MONGO_HOST=localhost MONGO_PORT=27017 MONGO_DATABASE=example_microservice_db ``` ## 🚀 Çalıştırma ### Development Mode ```bash # Tek instance npm run dev # Debug mode npm run dev:debug # Health check npm run health ``` ### Production Mode ```bash # PM2 ile cluster mode npm run cluster # Staging environment npm run cluster:staging ``` ### PM2 Yönetimi ```bash # PM2 işlemleri npm run pm2:start npm run pm2:stop npm run pm2:restart npm run pm2:logs npm run pm2:monitor ``` ## 📚 API Endpoints ### Health & Status - `GET /health` - Sağlık kontrolü - `GET /status` - Detaylı servis durumu - `GET /api/info` - Servis bilgileri ### Items API (Generic - Kendi endpoint'lerinizle değiştirin) - `GET /api/items` - Tüm item'ları listele - `GET /api/items/:id` - Tek item getir - `POST /api/items` - Yeni item oluştur - `PUT /api/items/:id` - Item güncelle - `DELETE /api/items/:id` - Item sil (kalıcı) - `GET /api/items/category/:category` - Kategoriye göre item'lar - `GET /api/items/search?q=query` - Item arama - `PUT /api/items/:id/status` - Status güncelle - `DELETE /api/items/:id/soft` - Soft delete - `POST /api/items/:id/restore` - Restore - `GET /api/items/stats` - İstatistikler - `GET /api/items/count` - Kayıt sayısı - `POST /api/items/bulk` - Toplu işlemler ### Debug & Special Endpoints - `GET /api/welcome` - Hoş geldin mesajı - `GET /api/debug` - Debug endpoint (returnLogs test için) ## 🔐 Authentication ### API Key Authentication Tüm isteklerde `x-api-key` header'ı gereklidir: ```bash curl -H "x-api-key: your-api-key-here" http://localhost:3000/api/products ``` ### JWT Authentication (Opsiyonel) ```bash curl -H "Authorization: Bearer your-jwt-token" http://localhost:3000/api/users ``` ## 🔧 Template Özelleştirme ### Model Özelleştirme `src/models/Item.js` dosyasını kendi model'inizle değiştirin: ```javascript import { CoreClass, mongoose } from 'core-microservice'; export class MyModel extends CoreClass { Schema() { return new mongoose.Schema({ id: { type: String, required: true, unique: true }, // Kendi alanlarınızı buraya ekleyin name: { type: String, required: true }, // ... }); } Collection() { return 'my_collection'; } Uniques() { return ['id']; } } ``` ### Controller Özelleştirme `src/controllers/ItemController.js` dosyasını güncelleyin: ```javascript import { BaseController } from 'core-microservice'; import { MyModel } from '../models/MyModel.js'; export class MyController extends BaseController { constructor() { super(MyModel); } // Custom endpoint'ler ekleyin async myCustomEndpoint(req, res, next) { // Custom logic } } ``` ## 🔍 Debug Özellikleri ### Request-Scoped Log Collection Mikroservisteki logları debug etmek için `returnLogs=true` header'ı kullanın: ```bash # Normal istek curl -H "x-api-key: your-key" http://localhost:3000/api/debug # Debug logları ile birlikte curl -H "x-api-key: your-key" -H "returnLogs: true" http://localhost:3000/api/debug ``` Response'da `_requestLogs` ve `_debugInfo` alanları gelir: ```json { "message": "Debug endpoint response", "_requestLogs": { "requestId": "req_1234567890_abc123", "microserviceId": "my-microservice", "duration": "45ms", "totalLogs": 8, "logs": [ { "timestamp": "2024-01-01T12:00:00.000Z", "type": "info", "message": "Debug endpoint çağrıldı", "requestId": "req_1234567890_abc123" } // ... diğer loglar ] }, "_debugInfo": { "requestId": "req_1234567890_abc123", "totalDuration": "45ms", "logCollection": "enabled" } } ``` ## 🏗️ Controller Örnekleri ### Custom Controller ```javascript import { BaseController } from 'core-microservice'; import { MyModel } from '../models/MyModel.js'; class MyController extends BaseController { constructor() { super(MyModel); } // Custom endpoint async customAction(req, res, next) { try { // Custom logic here return this.sendSuccess(res, data, 'Success message'); } catch (error) { next(error); } } // Override allowed filters getAllowedFilters() { return ['name', 'status', 'category']; } } ``` ## 📝 Environment Variables ### Temel Ayarlar ```env SERVICE_NAME=example-microservice SERVICE_VERSION=1.0.0 NODE_ENV=development PORT=3000 HOST=0.0.0.0 ``` ### Database ```env USE_MONGOOSE=true AUTO_CONNECT_DB=true MONGO_URI=mongodb+srv://... MONGO_MAX_POOL_SIZE=20 MONGO_MIN_POOL_SIZE=5 ``` ### Güvenlik ```env ENABLE_API_KEY_AUTH=true MICROSERVICE_API_KEY=your-api-key GATEWAY_API_KEY=your-gateway-key ENABLE_RATE_LIMIT=true RATE_LIMIT_MAX=1000 ``` ## 🔧 PM2 Konfigürasyonu `ecosystem.config.js` dosyası PM2 cluster ayarlarını içerir: - Development: 1 instance - Staging: 2 instance - Production: CPU çekirdeği kadar instance ## 📊 Monitoring ### Health Check ```bash curl http://localhost:3000/health ``` ### Status Check ```bash curl http://localhost:3000/status ``` ### PM2 Monitoring ```bash npm run pm2:monitor ``` ## 🧪 Test Etme ### API Test ```bash # Products curl -X GET "http://localhost:3000/api/products" -H "x-api-key: your-api-key" curl -X POST "http://localhost:3000/api/products" -H "x-api-key: your-api-key" -H "Content-Type: application/json" -d '{"name":"Test Product","price":100,"category":"electronics"}' # Users curl -X GET "http://localhost:3000/api/users" -H "x-api-key: your-api-key" curl -X POST "http://localhost:3000/api/users" -H "x-api-key: your-api-key" -H "Content-Type: application/json" -d '{"email":"test@example.com","firstName":"Test","lastName":"User"}' ``` ## 🚨 Error Handling Tüm hatalar structured format'ta döner: ```json { "status": false, "error": "Validation Error", "code": "VALIDATION_ERROR", "timestamp": "2024-01-01T12:00:00.000Z", "details": [...] } ``` ## 📈 Production Deployment ### 1. Environment Hazırlama ```bash # Production environment variables NODE_ENV=production PORT=3000 MONGO_URI=mongodb+srv://prod-connection-string ``` ### 2. PM2 ile Deploy ```bash npm run cluster ``` ### 3. Log Monitoring ```bash npm run pm2:logs ``` ## 🔍 Debugging ### Development ```bash npm run dev:debug ``` ### Production Logs ```bash # PM2 logs npm run pm2:logs # Log files tail -f logs/pm2-combined.log tail -f logs/pm2-error.log ``` ## 🤝 Katkıda Bulunma 1. Bu repo'yu fork edin 2. Feature branch oluşturun (`git checkout -b feature/amazing-feature`) 3. Commit yapın (`git commit -m 'Add amazing feature'`) 4. Push yapın (`git push origin feature/amazing-feature`) 5. Pull Request oluşturun ## 📄 Lisans MIT License ## 🆘 Destek - Core Package: [core-microservice](https://www.npmjs.com/package/core-microservice) - Issues: [GitHub Issues](https://github.com/your-repo/core-microservice/issues) ## 📚 Kaynaklar - [Core Microservice Documentation](https://github.com/your-repo/core-microservice) - [Express.js Guide](https://expressjs.com/) - [Mongoose Documentation](https://mongoosejs.com/) - [PM2 Documentation](https://pm2.keymetrics.io/)