core-microservice
v3.1.0
Published
Modern mikroservis core paketi - MongoDB 6.7, Express API, Mongoose, PM2 cluster desteği
Downloads
46
Maintainers
Readme
Core Microservice Package v2.1 🚀
Modern mikroservis geliştirme için full-stack altyapı paketi. MongoDB 6.7 + Mongoose + Express API + PM2 cluster desteği ile production-ready mikroservisler oluşturun.
🎉 v2.1 Yenilikleri: Database utilities, String utilities, Validation helpers, Auth middleware suite, Enhanced CoreClass ile metadata & status management!
📋 İçindekiler
- Bu Paket Nedir?
- Özellikler
- Kurulum
- Hızlı Başlangıç
- Database Utilities
- String Utilities
- Validation Utilities
- Auth Middleware Suite
- Database Yönetimi
- Core Sınıflar
- Logging
- Environment Variables
- Örnekler
🤔 Bu Paket Nedir?
Core Microservice Package, mikroservislerde ortak kullanılan temel işlevleri sağlayan minimal bir pakettir:
- ✅ MongoDB bağlantı yönetimi: Environment variable tabanlı, otomatik retry, connection pooling
- ✅ CoreClass: Temel CRUD işlemleri için base class
- ✅ MicroService: Servis başlatma ve yönetim sınıfı
- ✅ Winston Logging: Detaylı, structured logging
- ✅ Utility fonksiyonlar: Sık kullanılan yardımcı işlevler
- ✅ Error handling: Structured error management
🎯 Mikroservis Mimarisi
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Gateway │ │ Auth Service │ │ User Service │
│ (Auth, Cache) │ │ │ │ │
│ │ │ │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
└───────────────────────┼───────────────────────┘
│
┌─────────────────┐
│ Core Package │
│ (DB + Logging) │
└─────────────────┘🚀 Özellikler
🏗️ Modern Mikroservis Altyapısı
- ✅ Express API Server: Built-in HTTP server ve routing
- ✅ MongoDB 6.7 Driver: En yeni driver ile optimize performans
- ✅ Mongoose 8.0 Entegrasyonu: Şema tabanlı model yönetimi
- ✅ PM2 Cluster Desteği: Production-ready cluster çalışma
- ✅ Node.js v22 Uyumlu: En yeni Node.js özellikleri
🔐 Güvenlik & Auth Middleware Suite
- ✅ Multi-tenant City Key: Şehir bazlı multi-tenancy desteği
- ✅ User/Admin Authentication: JWT token tabanlı kimlik doğrulama
- ✅ Resource Ownership: Kaynak sahiplik kontrolü
- ✅ Rate Limiting: Kullanıcı bazlı istek sınırlama
- ✅ Request Validation: Alan doğrulama middleware'i
- ✅ API Key Doğrulama: Gateway entegrasyonu için built-in auth
- ✅ CORS Desteği: Cross-origin resource sharing
- ✅ Security Headers: Helmet ile güvenlik header'ları
🛠️ Core Utilities Suite
- ✅ Database Utils: Pagination, search, bulk operations
- ✅ String Utils: Türkçe karakter dönüşümü, slug üretimi, sanitization
- ✅ Validators: Email, telefon, fiyat, stok doğrulama
- ✅ Enhanced CoreClass: Metadata management, status tracking, bulk operations
🗄️ Gelişmiş Database Yönetimi
- ✅ MongoDB Atlas Ready: Cloud database tam desteği
- ✅ Mongoose + Native Driver: Her iki seçenek de mevcut
- ✅ Connection Pooling: Optimize edilmiş bağlantı yönetimi
- ✅ Auto Retry: Otomatik yeniden bağlanma
- ✅ Health Monitoring: Detaylı sağlık kontrolü
🏗️ Model & Controller Pattern
- ✅ CoreClass: Mongoose şema tabanlı base model
- ✅ BaseController: RESTful API controller'ları için base class
- ✅ Auto CRUD: Otomatik Create, Read, Update, Delete endpoints
- ✅ Validation: Built-in veri doğrulama sistemleri
📝 Advanced Logging & Monitoring
- ✅ Winston Structured Logging: JSON formatında detaylı loglar
- ✅ Request Logging: API istek/yanıt logları
- ✅ Performance Tracking: İşlem süresi takibi
- ✅ Error Handling: Kapsamlı hata yönetimi
- ✅ PM2 Log Integration: Cluster log yönetimi
🚀 Developer Experience
- ✅ Boilerplate Template: Hazır proje şablonu
- ✅ Hot Reload: Development modunda otomatik yenileme
- ✅ Environment Management: .env dosya desteği
- ✅ TypeScript Ready: Type definition'lar dahil
💻 Kurulum
npm install core-microservice🚀 Hızlı Başlangıç
1. Kurulum
npm install core-microservice2. Environment Variables
# MongoDB Atlas (Önerilen)
MONGO_URI=mongodb+srv://username:[email protected]/database?retryWrites=true&w=majority
# Servis Ayarları
SERVICE_NAME=my-microservice
SERVICE_VERSION=1.0.0
PORT=3000
# Güvenlik
MICROSERVICE_API_KEY=your-api-key-here
GATEWAY_API_KEY=your-gateway-key-here
# Mongoose ve Express
USE_MONGOOSE=true
ENABLE_API_KEY_AUTH=true
ENABLE_RATE_LIMIT=true3. Basit Mikroservis
import {
MicroService, CoreClass, BaseController, mongoose,
userAuth, validators, stringUtils
} from 'core-microservice';
// Model tanımla
class Product extends CoreClass {
Schema() {
return new mongoose.Schema({
id: { type: String, required: true, unique: true },
name: { type: String, required: true },
price: { type: Number, required: true },
category: { type: String, required: true }
});
}
Collection() { return 'products'; }
Uniques() { return ['id']; }
}
// Controller oluştur
class ProductController extends BaseController {
constructor() { super(Product); }
}
const controller = new ProductController();
// Mikroservis oluştur
const microservice = new MicroService({
name: 'product-service',
version: '1.0.0',
port: 3000,
routes: [
{ method: 'get', path: '/api/products', handler: controller.index.bind(controller) },
{ method: 'post', path: '/api/products', handler: controller.store.bind(controller) },
{ method: 'get', path: '/api/products/:id', handler: controller.show.bind(controller) }
]
});
// Servisi başlat
await microservice.start();
console.log('🚀 Mikroservis başlatıldı: http://localhost:3000');🛠️ Database Utilities
Modern database işlemleri için hazır utility fonksiyonları:
import { dbUtils, countWithFilters, paginateResults, generateSearchQuery } from 'core-microservice';
// Model instance ile kayıt sayma
const totalProducts = await countWithFilters(productInstance, { category: 'electronics' });
// Pagination hesaplama
const pagination = paginateResults(2, 20, 150); // page, limit, total
console.log(pagination);
// {
// page: 2, limit: 20, total: 150, pages: 8,
// hasNext: true, hasPrev: true, skip: 20,
// startRecord: 21, endRecord: 40, isEmpty: false
// }
// Arama query'si oluşturma
const searchQuery = generateSearchQuery('laptop', ['name', 'description'], {
caseSensitive: false,
exactMatch: false
});
console.log(searchQuery);
// { $or: [{ name: /laptop/i }, { description: /laptop/i }] }
// Gelişmiş filtreleme
const filters = buildAdvancedFilter(req.query, {
name: { type: 'string' },
price: { type: 'range' },
category: { type: 'array' },
createdAt: { type: 'date' }
});
// Toplu güncelleme
const updates = [
{ filter: { id: 'product1' }, data: { price: 100 } },
{ filter: { id: 'product2' }, data: { stock: 50 } }
];
const results = await bulkUpdate(productInstance, updates);🔤 String Utilities
Türkçe karakter desteği ve string işlemleri:
import { stringUtils, turkishToEnglish, createSlug, sanitizeText } from 'core-microservice';
// Türkçe karakterleri İngilizce'ye çevir
const text = turkishToEnglish('Çiğköfte şölen'); // 'Cigkofte solen'
// SEO dostu slug oluştur
const slug = createSlug('Türkçe Başlık Örneği', {
addTimestamp: true,
maxLength: 50,
removeStopWords: true
});
console.log(slug); // 'turkce-baslik-ornegi-1k3j5m9'
// Metin temizleme (güvenlik)
const cleanText = sanitizeText('<script>alert("xss")</script>Temiz metin', {
removeHtml: true,
removeScript: true,
removeSqlPatterns: true,
maxLength: 100
});
// Güçlü parola oluştur
const password = generatePassword({
length: 16,
includeSymbols: true,
excludeSimilar: true
});
// Metin benzerlik oranı
const similarity = calculateSimilarity('hello world', 'hello word'); // 0.89
// Metin analizi
const analysis = analyzeText('Bu bir örnek metindir. İçerik analiz edilecek.');
console.log(analysis);
// {
// characters: 45, charactersNoSpace: 37, words: 7,
// sentences: 2, paragraphs: 1, readingTime: 1
// }✅ Validation Utilities
Kapsamlı veri doğrulama fonksiyonları:
import { validators, isValidPrice, isValidEmail, validatePassword } from 'core-microservice';
// Fiyat doğrulama
const validPrice = isValidPrice(99.99, {
allowZero: false,
maxPrice: 10000,
maxDecimals: 2
}); // true
// E-posta doğrulama
const validEmail = isValidEmail('[email protected]', {
allowInternational: true,
maxLength: 100
}); // true
// Telefon doğrulama (Türkiye formatı)
const validPhone = isValidPhone('0532 123 45 67', {
country: 'TR',
format: 'flexible'
}); // true
// ID doğrulama
const validId = isValidId('user_1234567890abc', {
prefix: 'user',
minLength: 10,
allowedChars: 'alphanumeric-dash'
}); // true
// Parola güçlülük kontrolü
const passwordCheck = validatePassword('MyStr0ng!Pass', {
minLength: 8,
requireUppercase: true,
requireNumbers: true,
requireSymbols: true
});
console.log(passwordCheck);
// {
// isValid: true, score: 4,
// errors: [], suggestions: []
// }
// Stok doğrulama
const validStock = isValidStock(100, {
allowZero: true,
maxStock: 10000
}); // true🔐 Auth Middleware Suite
Kapsamlı kimlik doğrulama ve yetkilendirme:
import {
requireCity, requireUser, requireAdmin,
userAuth, adminAuth, publicWithCity,
requireOwnership, validateRequired
} from 'core-microservice';
// Multi-tenant city key doğrulama
app.use('/api', requireCity); // x-city-key header gerekli
// Kullanıcı doğrulama (API Gateway'den gelen token)
app.use('/api/user', requireUser); // x-user-id header gerekli
// Admin yetkisi
app.use('/api/admin', requireAdmin); // admin/super_admin role gerekli
// Kaynak sahiplik kontrolü
app.get('/api/posts/:id', requireOwnership(Post, 'id', 'userId'));
// Alan doğrulama
app.post('/api/posts', validateRequired(['title', 'content']));
// Kombine middleware setleri
app.use('/api/public', publicWithCity); // City + logging
app.use('/api/users', userAuth); // User + city + logging
app.use('/api/admin', adminAuth); // Admin + city + logging
// Rate limiting (kullanıcı bazlı)
app.use('/api', rateLimitByUser({
windowMs: 15 * 60 * 1000, // 15 dakika
maxRequests: 100 // 100 istek/kullanıcı
}));Enhanced CoreClass Features
import { CoreClass } from 'core-microservice';
class Product extends CoreClass {
// ... mevcut schema ve collection tanımları
// Bulk operations örneği
async createMultipleProducts(products) {
return await this.executeBulkOperation(products, 'create', {
batchSize: 50,
parallel: true,
continueOnError: true
});
}
}
const product = new Product();
// Metadata yönetimi
product.updateMetadata('lastEditor', 'user-123');
product.updateMetadata('tags', ['electronics', 'laptop']);
const tags = product.getMetadata('tags');
// Status yönetimi
product.updateStatus('active', ['draft', 'active', 'inactive'], {
reason: 'Product approved',
updatedBy: 'admin-456'
});
// Soft delete
await product.softDelete({
deletedBy: 'admin-123',
reason: 'Product discontinued'
});
// Restore
await product.restore({
restoredBy: 'admin-123',
newStatus: 'active'
});
// Touch (son aktivite güncellemesi)
product.touch();4. Boilerplate Kullan (Önerilen)
# Boilerplate'i kopyala
cp -r node_modules/core-microservice/boilerplate ./my-microservice
cd my-microservice
# Bağımlılıkları yükle
npm install
# Environment ayarla
cp env.example .env
# .env dosyasını düzenle
# Servisi başlat
npm run dev🗄️ Database Yönetimi
DatabaseManager
import { DatabaseManager } from 'core-microservice';
// Environment variable'lardan otomatik config
const dbManager = new DatabaseManager();
// Bağlantıyı başlat
await dbManager.connect();
// CRUD İşlemleri
await dbManager.insert('users', { name: 'John', email: '[email protected]' });
const users = await dbManager.find('users', { name: 'John' });
await dbManager.update('users', { name: 'John' }, { email: '[email protected]' });
await dbManager.remove('users', { name: 'John' });
// Health check
const health = await dbManager.healthCheck();
console.log(health); // { status: 'connected', pingTime: '5ms', database: 'my_db' }
// Bağlantıyı kapat
await dbManager.closeConnection();Legacy Database Functions
import { Query, Find, Insert, Update, Delete } from 'core-microservice';
// Legacy uyumluluk için
const users = await Query('users', { find: { status: 'active' } });
await Insert('users', { name: 'Jane', email: '[email protected]' });🏗️ Core Sınıflar
CoreClass ile Custom Model
import { CoreClass } from 'core-microservice';
class Product extends CoreClass {
constructor(data = {}) {
super();
this.setParameters(data, this.Parameters());
}
// Model parametrelerini tanımla
Parameters() {
return {
id: { type: "string", default: null },
name: { type: "string", default: null },
description: { type: "string", default: null },
price: { type: "money", default: 0 },
category: { type: "string", default: null },
stock: { type: "number", default: 0 },
isActive: { type: "boolean", default: true },
createdAt: { type: "date", default: Date.now() },
updatedAt: { type: "date", default: Date.now() }
};
}
// Collection adını belirt
Collection() {
return "products";
}
// Unique alanları belirt
Uniques() {
return ['name'];
}
// Özel metodlar
async findByCategory(category) {
return await this.GetAll({ category, isActive: true });
}
async updateStock(quantity) {
this.stock = quantity;
this.updatedAt = Date.now();
return await this.update();
}
}
// Kullanım
const product = new Product({
name: 'Laptop',
description: 'Gaming laptop',
price: 15000,
category: 'electronics',
stock: 10
});
await product.save(); // Insert veya update
const found = await product.find({ name: 'Laptop' });
const all = await product.GetAll({ category: 'electronics' });Custom Model Kullanımı
Package artık hazır model içermez. İhtiyacınıza göre CoreClass'dan türeterek kendi modellerinizi oluşturun:
import { CoreClass } from 'core-microservice';
// Kendi modelinizi oluşturun
class MyModel extends CoreClass {
constructor(data = {}) {
super();
this.setParameters(data, this.Parameters());
}
Parameters() {
return {
id: { type: "string", default: null },
name: { type: "string", default: null },
status: { type: "string", default: "active" },
createdAt: { type: "date", default: Date.now() }
};
}
Collection() { return "my_collection"; }
Uniques() { return ['name']; }
}
// Kullanım
const item = new MyModel({ name: 'Test Item' });
await item.save();📝 Logging
import { logger } from 'core-microservice';
// Temel logging
logger.info('Servis başlatıldı');
logger.error('Hata oluştu', { error: error.message, userId: '123' });
logger.warn('Uyarı mesajı', { details: 'some data' });
logger.debug('Debug bilgisi');
// Structured logging - otomatik olarak JSON formatında
logger.info('User created', {
userId: 'user-123',
email: '[email protected]',
timestamp: new Date(),
duration: '45ms'
});🌍 Environment Variables
# MongoDB Ayarları (Zorunlu)
MONGO_HOST=localhost # Tek host için
MONGO_PORT=27017 # Port
MONGO_DATABASE=my_microservice_db # Database adı
# MongoDB Auth (Opsiyonel)
MONGO_USER=username
MONGO_PASSWORD=password
MONGO_AUTH_SOURCE=admin
# Replica Set (Opsiyonel)
MONGO_REPLICA_SET=rs0
MONGO_HOSTS=host1:27017,host2:27017 # MONGO_HOST yerine kullanın
# Örnekler
# Lokal development (auth olmadan)
MONGO_HOST=localhost
MONGO_PORT=27017
MONGO_DATABASE=my_dev_db
# Production (auth ile)
MONGO_HOST=prod-mongo.example.com
MONGO_PORT=27017
MONGO_DATABASE=my_prod_db
MONGO_USER=app_user
MONGO_PASSWORD=secure_password
MONGO_AUTH_SOURCE=admin
# Replica Set
MONGO_HOSTS=mongo1.example.com:27017,mongo2.example.com:27017,mongo3.example.com:27017
MONGO_DATABASE=my_cluster_db
MONGO_USER=cluster_user
MONGO_PASSWORD=cluster_password
MONGO_REPLICA_SET=rs0📖 API Örnekleri
REST API Endpoints
Otomatik oluşturulan endpoints:
# Health Check
GET /health
GET /status
GET /api/info
# CRUD Endpoints (BaseController)
GET /api/products # Tüm ürünler
GET /api/products/:id # Tek ürün
POST /api/products # Yeni ürün
PUT /api/products/:id # Ürün güncelle
DELETE /api/products/:id # Ürün sil
GET /api/products/count # Sayım
POST /api/products/bulk # Toplu işlemAPI Key Authentication
Tüm isteklerde x-api-key header'ı gereklidir:
curl -H "x-api-key: your-api-key" http://localhost:3000/api/productsModel & Controller Örneği
import { CoreClass, BaseController, mongoose } from 'core-microservice';
// Modern Mongoose Model
class User extends CoreClass {
Schema() {
return new mongoose.Schema({
id: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
role: { type: String, enum: ['user', 'admin'], default: 'user' },
isActive: { type: Boolean, default: true }
}, { timestamps: true });
}
Collection() { return 'users'; }
Uniques() { return ['id', 'email']; }
// Custom methods
async findByEmail(email) {
return await this.find({ email });
}
}
// Custom Controller
class UserController extends BaseController {
constructor() {
super(User);
}
// Custom endpoint
async getByEmail(req, res, next) {
try {
const { email } = req.params;
const user = new User();
const found = await user.findByEmail(email);
if (found) {
return this.sendSuccess(res, user.toJSON(), 'User found');
} else {
return this.sendError(res, 'User not found', 404);
}
} catch (error) {
next(error);
}
}
}PM2 Cluster Kullanımı
# Development
npm run dev
# Production Cluster
npm run cluster
# PM2 Commands
npm run pm2:start
npm run pm2:stop
npm run pm2:logs
npm run pm2:monitorAdvanced Mikroservis
import { MicroService, logger } from 'core-microservice';
import { ProductController } from './controllers/ProductController.js';
const productController = new ProductController();
const microservice = new MicroService({
name: 'advanced-service',
version: '2.0.0',
port: 3000,
// Custom routes
routes: [
{ method: 'get', path: '/api/products', handler: productController.index.bind(productController) },
{ method: 'post', path: '/api/products', handler: productController.store.bind(productController) },
{ method: 'get', path: '/api/products/search', handler: productController.search.bind(productController) }
],
// Lifecycle hooks
beforeStart: async (service) => {
logger.info('🚀 Starting service...');
},
afterStart: async (service) => {
logger.info('✅ Service ready!');
}
});
await microservice.start();🚀 Örnek Çalıştırma
# Paket kurulumunu test et
git clone https://github.com/your-repo/core-microservice.git
cd core-microservice
npm install
# Environment variables ayarla
cp .env.example .env
# .env dosyasını MongoDB ayarlarınızla güncelleyin
# Örnekleri çalıştır
node examples/basic-usage.js🔄 Migration Guide
Eski Versiyondan Geçiş
// ESKİ (v1.0.8)
import { Auth, Cache, createDatabaseManager } from 'core-microservice';
// YENİ (v1.0.9+)
import { MicroService, DatabaseManager, logger } from 'core-microservice';
// Auth ve Cache işlemleri artık gateway'de yapılacak📝 Lisans
MIT License
🤝 Katkıda Bulunma
- Fork yapın
- Feature branch oluşturun (
git checkout -b feature/amazing-feature) - Commit yapın (
git commit -m 'Add amazing feature') - Push yapın (
git push origin feature/amazing-feature) - Pull Request oluşturun
📞 İletişim
- GitHub Issues: Sorun bildirin
- Paket: NPM
