Web Worker Support

Ecosistema completo para organización y gestión de contenido con interfaces espaciales

⚙️ Web Worker Integration

Optional dedicated Web Worker support for heavy I/O operations, ensuring the main thread stays responsive during intensive storage operations.


🚀 Benefits

Performance Advantages

Use Cases


🔧 Setup

Basic Configuration

// app.config.ts
import { provideGgStorageWorker } from '@storage-system';

export const appConfig: ApplicationConfig = {
  providers: [
    provideGgStorageWorker({
      config: {
        namespace: 'myapp',
        cache: { maxItems: 1000, ttlMs: 300000 },
        useWorker: true
      },
      workerFactory: () => new Worker(
        new URL('libs/storage-worker/src/lib/worker.ts', import.meta.url),
        { type: 'module' }
      )
    })
  ]
};

Advanced Configuration

provideGgStorageWorker({
  config: {
    namespace: 'myapp',
    cache: { maxItems: 2000, ttlMs: 600000 },
    useWorker: true,
    performance: {
      batchProcessing: true,   // Enable batch processing in worker
      monitoring: true,        // Enable performance monitoring
      batchSize: 100,          // Larger batches in worker
      batchDelay: 50           // Shorter delays for worker processing
    }
  },
  workerFactory: () => new Worker(
    new URL('./custom-storage-worker.ts', import.meta.url),
    { type: 'module' }
  )
})

📊 Transparent Operation

The Angular StorageService works exactly the same - all operations are transparently offloaded to the worker:

@Component({
  selector: 'app-data-processor',
  template: `
    <button (click)="processLargeDataset()" [disabled]="processing()">
      {{ processing() ? 'Processing...' : 'Process Data' }}
    </button>
  `
})
export class DataProcessorComponent {
  private storage = inject(StorageService);
  processing = signal(false);

  async processLargeDataset() {
    this.processing.set(true);
    
    try {
      // This automatically runs in worker - UI stays responsive!
      await this.storage.put('processed-data', {
        results: this.generateLargeDataset(),
        timestamp: Date.now()
      });
      
      console.log('✅ Large dataset processed without blocking UI');
    } finally {
      this.processing.set(false);
    }
  }
  
  private generateLargeDataset() {
    // Generate MB of data
    return Array(100000).fill(null).map((_, i) => ({
      id: i,
      data: `Item ${i} with lots of data...`.repeat(100)
    }));
  }
}

🛡️ Automatic Fallback

If worker creation fails, operations automatically use the main thread with no code changes required:

// Works in all scenarios:
// ✅ Worker available → uses worker for performance
// ✅ Worker unavailable → uses main thread seamlessly
// ✅ Worker fails → automatic fallback to main thread
await storage.put('data', value);

🎯 Best Practices

1. Trust the System

// ✅ GOOD: Let the system handle worker usage automatically
await storage.put('large-dataset', massiveData);

// ❌ UNNECESSARY: Don't try to manage workers manually
// The worker is completely transparent

2. Use for Heavy Operations

// ✅ PERFECT for worker usage:
// - Large datasets
// - Bulk operations  
// - Data migrations
// - Background processing

async importBulkData(items: DataItem[]) {
  // All operations automatically use worker
  const results = await Promise.all(
    items.map(item => storage.put(`import/${item.id}`, item))
  );
  return results.filter(Boolean).length;
}

3. Monitor Performance

// Check worker capabilities
const capabilities = storage.getCapabilities();
console.log('Worker available:', capabilities.worker);

// Monitor performance
const stats = storage.getPerformanceStats();
console.log('Performance stats:', stats);

🔮 Implementation Details

Worker Architecture

Performance Characteristics


📚 Related Documentation


Web Worker integration provides powerful performance benefits while maintaining the same simple, intelligent API! ⚡