Dexie.js Integration
Ecosistema completo para organización y gestión de contenido con interfaces espaciales
Dexie.js Integration
Our storage system uses Dexie.js as the modern, intelligent IndexedDB wrapper. Dexie.js provides superior performance, automatic schema management, and advanced querying capabilities compared to raw IndexedDB.
🚀 Why Dexie.js?
- Automatic Schema Management: No manual IndexedDB setup required
- Intelligent Migrations: Seamless database upgrades
- Performance Optimized: Built-in query optimization and caching
- Type Safety: Full TypeScript support with proper typing
- Advanced Features: Compression, cleanup, and monitoring
🧠 Intelligent Features
Automatic Compression
// Data > 1KB is automatically compressed
await storage.put('large-dataset', massiveObject); // Auto-compressed
await storage.put('small-config', { theme: 'dark' }); // Stored as-is
Smart Caching
// In-memory LRU cache with 50MB limit
const data = await storage.get('frequently-accessed'); // Cache hit
const data2 = await storage.get('frequently-accessed'); // Instant return
Automatic Cleanup
// Expired entries are automatically removed
await storage.put('temp-data', value, { ttlMs: 60000 }); // 1 minute TTL
// After 1 minute, data is automatically cleaned up
📊 Performance Monitoring
Built-in Statistics
// Get performance statistics through the StorageService
const storage = inject(StorageService);
const stats = storage.getPerformanceStats();
if (stats) {
console.log('Storage Statistics:', {
cacheHitRate: stats.cacheHitRate,
avgDuration: stats.avgDuration,
totalOperations: stats.totalOperations,
adapterUsage: stats.adapterUsage
});
}
// Get micro-cache statistics
const microStats = storage.getMicroCacheStats();
console.log('Micro-cache Stats:', {
size: microStats.size,
budget: microStats.budget,
hitRate: microStats.hitRate
});
Performance Optimization
// Performance optimization is handled automatically by the intelligent system
// - Automatic compression for large data (>1KB)
// - Smart caching with LRU eviction
// - Automatic cleanup of expired entries
// - Batch processing for multiple operations
// Manual performance metrics clearing when needed
storage.clearPerformanceMetrics();
🔧 Advanced Configuration
Schema Customization
The Dexie adapter automatically creates optimized indexes:
// Automatic indexes for performance
{
key: 'primary key',
timestamp: 'for cleanup queries',
size: 'for size-based operations',
type: 'for type filtering',
compressed: 'for compression stats',
expiresAt: 'for TTL cleanup'
}
Intelligent Data Analysis
// Automatic data type detection
await storage.put('user-profile', userObject); // type: 'object'
await storage.put('user-preferences', ['dark', 'en']); // type: 'array'
await storage.put('last-login', new Date()); // type: 'date'
🔄 Integration with Storage System
Automatic Selection
// System automatically chooses Dexie when appropriate
const storage = inject(StorageService);
// Large structured data → Dexie.js
await storage.put('analytics/report', largeReport);
// Critical data → Dexie.js + localStorage (redundancy)
await storage.put('user/auth-token', token);
Configuration Options
// app.config.ts
providers: [
...provideGgStorage({
namespace: 'myapp',
strategy: 'balanced', // Use balanced strategy (recommended)
adapterPreference: 'dexie', // Prefer Dexie.js when available
performance: {
adaptiveStrategy: true, // Enable intelligent adapter selection
redundancy: true, // Enable smart data mirroring
monitoring: true, // Enable performance tracking
batchProcessing: true, // Enable operation batching
microCacheBudget: 100 * 1024 // 100KB micro-cache budget
}
})
]
🛠️ Development & Debugging
Performance Monitoring
// Enable detailed monitoring through configuration
const storage = inject(StorageService);
// Check current adapter being used
console.log('Current adapter:', storage.adapterKind); // 'dexie' | 'opfs' | 'localStorage'
// Get performance statistics (when monitoring enabled)
const stats = storage.getPerformanceStats();
if (stats) {
console.log('Performance Stats:', stats);
}
// Get detailed performance report (when monitoring enabled)
const report = storage.getPerformanceReport();
if (report) {
console.log('Performance Report:', report);
}
Strategy and Configuration Management
// Get current strategy
const currentStrategy = storage.getStrategy();
console.log('Current Strategy:', currentStrategy); // 'speed' | 'balanced' | 'durable'
// Change strategy at runtime
storage.setStrategy('durable'); // Switch to maximum reliability
// Get storage capabilities
const capabilities = storage.getCapabilities();
console.log('Storage Capabilities:', capabilities);
// Get current configuration
const config = storage.config;
console.log('Storage Config:', config);
Development Tools
// Switch adapters for testing (development only)
if (environment.development) {
console.log('Testing different adapters...');
// Test with Dexie.js
storage.switchAdapter('dexie');
console.log('Now using:', storage.adapterKind);
// Test with OPFS
if (storage.getCapabilities().opfs) {
storage.switchAdapter('opfs');
console.log('Now using:', storage.adapterKind);
}
// Clear performance metrics for clean testing
storage.clearPerformanceMetrics();
}
📈 Best Practices
1. Let the System Decide
// ✅ Good - Let intelligent selection work
await storage.put('user/profile', userData);
// ❌ Avoid - Manual adapter switching unless necessary
storage.switchAdapter('dexie');
await storage.put('user/profile', userData);
2. Use Appropriate Data Structures
// ✅ Good - Structured data perfect for Dexie.js
await storage.put('analytics/events', {
events: [...],
metadata: {...},
timestamp: Date.now()
});
// ✅ Good - Simple strings work well too
await storage.put('user/theme', 'dark');
3. Leverage TTL for Temporary Data
// ✅ Good - Automatic cleanup
await storage.put('cache/api-response', data, { ttlMs: 300000 }); // 5 min
// ✅ Good - Session data
await storage.put('session/temp', sessionData, { ttlMs: 3600000 }); // 1 hour
4. Monitor Performance
// Import environment for development checks
import { environment } from '../environments/environment';
// ✅ Good - Regular monitoring in development
if (environment.development) {
const stats = storage.getPerformanceStats();
if (stats) {
console.log('Storage Performance:', stats);
}
const microStats = storage.getMicroCacheStats();
console.log('Micro-cache Performance:', microStats);
}
🔮 Future Enhancements
- Advanced Compression: LZ-string integration for better compression ratios
- Query Optimization: Smart indexing based on access patterns
- Background Sync: Automatic synchronization with cloud services
- Predictive Caching: ML-based cache warming
- Cross-Tab Coordination: Intelligent cache sharing between tabs
🚨 Migration Notes
If upgrading from raw IndexedDB:
- Automatic Migration: Dexie.js handles schema migrations automatically
- Data Preservation: Existing data is preserved and enhanced
- Performance Boost: Immediate performance improvements
- New Features: Access to compression, caching, and monitoring
The storage system seamlessly handles the transition - no code changes required!