UNPKG

@krunal_tarale-5/ultimate-streaming-package

Version:

🚀 Ultimate Real-Time Streaming Package v2.1.9 - Multi-Platform, Multi-Collection Architecture with Native MongoDB & MySQL Support, 99.96% Performance Improvement. Enterprise-grade real-time data streaming with Socket.IO integration, dynamic schema evolut

562 lines (447 loc) 13.7 kB
# 📚 API Reference **Complete API documentation for Ultimate Streaming Package v2.1.4** ## 🚀 **Core Methods** ### `init(config)` Initialize the streaming package with database configuration. **Parameters:** - `config` (Object): Database configuration object **Returns:** Promise **Example:** ```javascript await UltimateStreamer.init({ dbType: 'mysql', // 'mysql' or 'mongodb' host: 'localhost', port: 3306, // 27017 for MongoDB database: 'myapp', user: 'root', // MySQL only password: '', // MySQL only enableCache: true, debug: false, pollingInterval: 2000 }); ``` **Configuration Options:** | Option | Type | Default | Description | |--------|------|---------|-------------| | `dbType` | string | 'mysql' | Database type ('mysql' or 'mongodb') | | `host` | string | 'localhost' | Database host | | `port` | number | 3306/27017 | Database port | | `database` | string | - | Database name | | `user` | string | - | Database user (MySQL only) | | `password` | string | - | Database password (MySQL only) | | `enableCache` | boolean | true | Enable caching | | `debug` | boolean | false | Enable debug mode | | `pollingInterval` | number | 2000 | Polling interval (ms) | | `maxConnections` | number | 10 | Maximum connections (MySQL) | | `acquireTimeout` | number | 60000 | Connection timeout (ms) | ### `push(collection, data)` Push data to a native table/collection. **Parameters:** - `collection` (string): Collection/table name - `data` (Object): Data to push **Returns:** Promise<Object> **Example:** ```javascript const result = await UltimateStreamer.push('orders', { orderId: 'ORD-001', customerId: 'CUST-001', total: 1500.00, status: 'pending' }); console.log('Push result:', result); // Output: { success: true, id: 'generated-id' } ``` ### `get(collection, query)` Get data from a collection/table with optional query. **Parameters:** - `collection` (string): Collection/table name - `query` (Object, optional): Query object **Returns:** Promise<Array> **Example:** ```javascript // Get all orders const allOrders = await UltimateStreamer.get('orders'); // Get pending orders const pendingOrders = await UltimateStreamer.get('orders', { where: { status: 'pending' } }); // Get orders with total > 1000 const highValueOrders = await UltimateStreamer.get('orders', { where: { total: { $gt: 1000 } } }); // Get user by email const user = await UltimateStreamer.get('users', { where: { email: 'john@example.com' } }); ``` ### `update(collection, query, data)` Update existing data in a collection/table. **Parameters:** - `collection` (string): Collection/table name - `query` (Object): Query to find records to update - `data` (Object): New data to update **Returns:** Promise<Object> **Example:** ```javascript const result = await UltimateStreamer.update('orders', { orderId: 'ORD-001' }, // Find this order { status: 'shipped', shippedAt: new Date(), trackingNumber: 'TRK-123456' } ); console.log('Updated:', result.found); // true/false console.log('Affected rows:', result.affectedRows); ``` ### `on(collection, callback)` Listen for real-time updates on a collection/table. **Parameters:** - `collection` (string): Collection/table name - `callback` (Function): Callback function **Returns:** void **Example:** ```javascript UltimateStreamer.on('orders', (data, meta) => { console.log('Order update:', data.orderId, meta.changeType); // meta.changeType can be: 'created', 'updated', 'deleted' }); UltimateStreamer.on('users', (data, meta) => { console.log('User update:', data.userId, meta.changeType); updateUserDashboard(data); }); ``` ## 🔧 **Advanced Methods** ### `delete(collection, query)` Delete data from a collection/table. **Parameters:** - `collection` (string): Collection/table name - `query` (Object): Query to find records to delete **Returns:** Promise<Object> **Example:** ```javascript const result = await UltimateStreamer.delete('orders', { orderId: 'ORD-001' }); console.log('Deleted:', result.found); // true/false console.log('Affected rows:', result.affectedRows); ``` ### `count(collection, query)` Count records in a collection/table. **Parameters:** - `collection` (string): Collection/table name - `query` (Object, optional): Query object **Returns:** Promise<number> **Example:** ```javascript // Count all orders const totalOrders = await UltimateStreamer.count('orders'); // Count pending orders const pendingCount = await UltimateStreamer.count('orders', { where: { status: 'pending' } }); console.log('Total orders:', totalOrders); console.log('Pending orders:', pendingCount); ``` ### `exists(collection, query)` Check if records exist in a collection/table. **Parameters:** - `collection` (string): Collection/table name - `query` (Object): Query object **Returns:** Promise<boolean> **Example:** ```javascript const userExists = await UltimateStreamer.exists('users', { email: 'john@example.com' }); if (userExists) { console.log('User already exists'); } else { console.log('User not found'); } ``` ## 📊 **Query Operators** ### Comparison Operators | Operator | Description | Example | |----------|-------------|---------| | `$eq` | Equal | `{ status: { $eq: 'pending' } }` | | `$ne` | Not equal | `{ status: { $ne: 'cancelled' } }` | | `$gt` | Greater than | `{ total: { $gt: 1000 } }` | | `$gte` | Greater than or equal | `{ total: { $gte: 1000 } }` | | `$lt` | Less than | `{ total: { $lt: 1000 } }` | | `$lte` | Less than or equal | `{ total: { $lte: 1000 } }` | | `$in` | In array | `{ status: { $in: ['pending', 'shipped'] } }` | | `$nin` | Not in array | `{ status: { $nin: ['cancelled'] } }` | ### Logical Operators | Operator | Description | Example | |----------|-------------|---------| | `$and` | Logical AND | `{ $and: [{ status: 'pending' }, { total: { $gt: 1000 } }] }` | | `$or` | Logical OR | `{ $or: [{ status: 'pending' }, { status: 'shipped' }] }` | | `$not` | Logical NOT | `{ status: { $not: 'cancelled' } }` | ### String Operators | Operator | Description | Example | |----------|-------------|---------| | `$regex` | Regular expression | `{ email: { $regex: '@gmail.com$' } }` | | `$like` | SQL LIKE | `{ name: { $like: '%john%' } }` | ## 🎯 **Real-World Examples** ### E-commerce Platform ```javascript // Initialize await UltimateStreamer.init({ dbType: 'mysql', host: 'localhost', port: 3306, database: 'ecommerce', user: 'root', password: '', enableCache: true }); // Push orders await UltimateStreamer.push('orders', { orderId: 'ORD-001', customerId: 'CUST-001', total: 1500.00, status: 'pending', items: [ { productId: 'PROD-001', quantity: 2, price: 750.00 } ], createdAt: new Date() }); // Push users await UltimateStreamer.push('users', { userId: 'USR-001', email: 'john@example.com', name: 'John Doe', role: 'customer', lastLogin: new Date() }); // Push products await UltimateStreamer.push('products', { productId: 'PROD-001', name: 'Gaming Laptop', price: 999.99, stock: 50, category: 'electronics' }); // Real-time monitoring UltimateStreamer.on('orders', (data, meta) => { console.log('📦 Order update:', data.orderId, meta.changeType); if (meta.changeType === 'updated' && data.status === 'shipped') { notifyCustomer(data.customerId, `Order ${data.orderId} shipped!`); } }); UltimateStreamer.on('users', (data, meta) => { console.log('👤 User update:', data.userId, meta.changeType); updateUserAnalytics(data); }); UltimateStreamer.on('products', (data, meta) => { console.log('🛍️ Product update:', data.productId, meta.changeType); if (data.stock < 10) { sendLowStockAlert(data); } }); // Query examples const pendingOrders = await UltimateStreamer.get('orders', { where: { status: 'pending' } }); const highValueOrders = await UltimateStreamer.get('orders', { where: { total: { $gt: 1000 } } }); const userByEmail = await UltimateStreamer.get('users', { where: { email: 'john@example.com' } }); // Update examples await UltimateStreamer.update('orders', { orderId: 'ORD-001' }, { status: 'shipped', shippedAt: new Date(), trackingNumber: 'TRK-123456' } ); await UltimateStreamer.update('users', { userId: 'USR-001' }, { lastLogin: new Date(), loginCount: { $inc: 1 } } ); ``` ### Analytics Dashboard ```javascript // Initialize await UltimateStreamer.init({ dbType: 'mysql', host: 'localhost', port: 3306, database: 'analytics', user: 'root', password: '', enableCache: true }); // Push analytics data await UltimateStreamer.push('social_media_analytics', { platform: 'twitter', followers: 125000, tweets: 15420, engagement: 8.5, timestamp: new Date() }); await UltimateStreamer.push('website_analytics', { page: '/home', visitors: 15420, bounceRate: 23.5, avgTimeOnPage: 180, timestamp: new Date() }); await UltimateStreamer.push('sales_analytics', { date: '2024-01-15', revenue: 45000.00, orders: 125, avgOrderValue: 360.00, timestamp: new Date() }); // Real-time monitoring UltimateStreamer.on('social_media_analytics', (data, meta) => { console.log('📊 Social media update:', data.platform, data.followers); updateSocialMediaDashboard(data); }); UltimateStreamer.on('website_analytics', (data, meta) => { console.log('🌐 Website update:', data.page, data.visitors); updateWebsiteDashboard(data); }); UltimateStreamer.on('sales_analytics', (data, meta) => { console.log('💰 Sales update:', data.date, data.revenue); updateSalesDashboard(data); }); // Query examples const todaySales = await UltimateStreamer.get('sales_analytics', { where: { date: '2024-01-15' } }); const highEngagement = await UltimateStreamer.get('social_media_analytics', { where: { engagement: { $gt: 5 } } }); const popularPages = await UltimateStreamer.get('website_analytics', { where: { visitors: { $gt: 1000 } } }); ``` ## 🔍 **Error Handling** ### Common Errors and Solutions **1. Connection Error** ```javascript try { await UltimateStreamer.init({ dbType: 'mysql', host: 'localhost', port: 3306, database: 'myapp', user: 'root', password: '' }); } catch (error) { console.error('Connection failed:', error.message); // Check if database is running // Check credentials // Check network connectivity } ``` **2. Collection Not Found** ```javascript try { const data = await UltimateStreamer.get('nonexistent_collection'); } catch (error) { console.error('Collection not found:', error.message); // Collection will be created automatically on first push } ``` **3. Query Error** ```javascript try { const data = await UltimateStreamer.get('orders', { where: { invalid_field: 'value' } }); } catch (error) { console.error('Query error:', error.message); // Check field names // Check query syntax } ``` ## 📈 **Performance Tips** ### 1. Enable Caching ```javascript await UltimateStreamer.init({ // ... other config enableCache: true // This improves performance significantly }); ``` ### 2. Use Specific Queries ```javascript // ✅ Good: Specific queries const pendingOrders = await UltimateStreamer.get('orders', { where: { status: 'pending' } }); // ❌ Avoid: Getting all data const allOrders = await UltimateStreamer.get('orders'); const pendingOrders = allOrders.filter(order => order.status === 'pending'); ``` ### 3. Batch Operations ```javascript // ✅ Good: Batch operations const orders = [ { orderId: 'ORD-001', total: 1000 }, { orderId: 'ORD-002', total: 2000 }, { orderId: 'ORD-003', total: 3000 } ]; for (const order of orders) { await UltimateStreamer.push('orders', order); } ``` ### 4. Optimize Real-time Listeners ```javascript // ✅ Good: Specific listeners UltimateStreamer.on('orders', (data, meta) => { if (meta.changeType === 'updated' && data.status === 'shipped') { notifyCustomer(data.customerId); } }); // ❌ Avoid: Processing all updates UltimateStreamer.on('orders', (data, meta) => { // This runs for every order update processAllUpdates(data); }); ``` ## 🚀 **Migration from v1.x** ### API Changes | v1.x | v2.x | Notes | |------|------|-------| | `push('key', data)` | `push('collection', data)` | Same API, creates native collections | | `on('key', callback)` | `on('collection', callback)` | Same API, per-collection monitoring | | `get('key')` | `get('collection', query)` | Enhanced with query support | | `update('key', data)` | `update('collection', query, data)` | Enhanced with query support | ### Migration Example **Before (v1.x):** ```javascript await UltimateStreamer.push('users', userData); UltimateStreamer.on('users', callback); const data = await UltimateStreamer.get('users'); ``` **After (v2.x):** ```javascript await UltimateStreamer.push('users', userData); UltimateStreamer.on('users', callback); const data = await UltimateStreamer.get('users', { where: { active: true } }); ``` ## 📚 **Next Steps** 1. **Try the examples** above to see the API in action 2. **Check the [Quick Start Guide](../quick-start/)** for basic setup 3. **Explore [Integration Guides](../integration/)** for framework-specific setup 4. **Review [Performance Benchmarks](../benchmarks/)** for optimization tips ## 🤝 **Need Help?** - **Documentation**: [Complete Documentation](../) - **GitHub Issues**: [Report bugs or request features](https://github.com/krunal-tarale/ultimate-streaming-package/issues) - **Email Support**: [krunaltarale555@gmail.com](mailto:krunaltarale555@gmail.com) --- **Ready to build amazing real-time applications?** 🚀 ```bash npm install @krunal_tarale-5/ultimate-streaming-package@2.1.4 ```