Advanced

The Aurelia Fetch Client offers powerful advanced features for enterprise applications, including sophisticated caching, request monitoring, custom interceptor patterns, and integration with complex authentication systems.

Advanced Header Management

Dynamic Authorization Headers

Headers can be functions that are evaluated for each request, perfect for handling token refresh scenarios:

import { IHttpClient } from '@aurelia/fetch-client';
import { resolve } from '@aurelia/kernel';

export class AuthenticatedApiService {
  private http = resolve(IHttpClient);
  private tokenStorage = new TokenStorage();

  constructor() {
    this.http.configure(config => config
      .withDefaults({
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': () => {
            const token = this.tokenStorage.getAccessToken();
            return token ? `Bearer ${token}` : '';
          },
          'X-Client-Version': () => this.getClientVersion(),
          'X-Request-ID': () => this.generateRequestId()
        }
      })
    );
  }

  private getClientVersion(): string {
    return process.env.APP_VERSION || '1.0.0';
  }

  private generateRequestId(): string {
    return `${Date.now()}-${Math.random().toString(36).substring(2)}`;
  }
}

class TokenStorage {
  getAccessToken(): string | null {
    const tokenData = localStorage.getItem('auth_tokens');
    if (!tokenData) return null;

    const { accessToken, expiresAt } = JSON.parse(tokenData);
    
    // Check if token is expired
    if (Date.now() >= expiresAt) {
      this.refreshToken();
      return this.getAccessToken(); // Recursive call after refresh
    }

    return accessToken;
  }

  private refreshToken(): void {
    // Token refresh logic here
    // This is synchronous for simplicity, but could be async
  }
}

Conditional Headers

Apply different headers based on request characteristics:

Built-in Cache Interceptor

The fetch client includes a sophisticated caching system with multiple storage options:

Custom Cache Storage

Use different storage backends for caching:

Request Tracking and Lifecycle Management

The HttpClient provides built-in request tracking capabilities that enable you to monitor active requests and respond to request lifecycle events. This is essential for building loading indicators, progress tracking, and request coordination features.

Built-in Request Properties

The HttpClient exposes two key properties for request tracking:

Key Properties:

  • activeRequestCount: The current number of active requests (including those being processed by interceptors)

  • isRequesting: Boolean indicating whether one or more requests are currently active

Request Lifecycle Events

The HttpClient can dispatch DOM events for request lifecycle tracking. This requires configuring an event dispatcher using withDispatcher().

Available Events

  • started: Fired when the first request starts (when activeRequestCount goes from 0 to 1)

  • drained: Fired when all requests complete (when activeRequestCount returns to 0)

Configuring Event Dispatcher

Building a Loading Indicator

Use request tracking to implement a global loading indicator:

Advanced Request Monitoring

Combine built-in tracking with custom monitoring:

Progress Tracking Component

Build a reactive progress tracker:

Request Queue Visualization

Display active requests in real-time:

Best Practices for Request Tracking

1. Use Events for UI Updates

Prefer lifecycle events over polling for UI updates:

2. Single Event Dispatcher

Configure the dispatcher once during initialization:

3. Cleanup Event Listeners

Always remove event listeners when components are destroyed:

4. Combine with Interceptors

Use interceptors for detailed request tracking:

Summary

Request tracking provides:

  • activeRequestCount: Number of currently active requests

  • isRequesting: Boolean indicating if any requests are active

  • HttpClientEvent.started: Fired when first request starts

  • HttpClientEvent.drained: Fired when all requests complete

  • withDispatcher(node): Configure DOM node for event dispatching

These features enable robust loading indicators, progress tracking, and request coordination in your applications.

Advanced Authentication Patterns

Automatic Token Refresh

Handle token expiration and refresh transparently:

Request Batching and Coordination

Request Deduplication

Prevent duplicate concurrent requests:

Request Queuing

Queue and coordinate multiple requests:

Performance Optimization

Request Timeout Management

Implement sophisticated timeout handling:

Response Compression Handling

Handle compressed responses efficiently:

Testing and Debugging Support

Request/Response Logging

Comprehensive logging for development and debugging:

These advanced patterns demonstrate the full power of the Aurelia Fetch Client for enterprise applications. The combination of interceptors, event monitoring, caching, and authentication patterns provides a robust foundation for complex HTTP client requirements.

Last updated

Was this helpful?