This guide covers advanced utilities, lifecycle methods, error handling, and cache implementation details for the Aurelia Fetch Client.
Advanced HttpClient Methods
buildRequest()
The buildRequest() method allows you to construct a Request object using the HttpClient's configuration without actually sending the request. This is useful for request inspection, manual request manipulation, or integration with other libraries.
// Install a fetch polyfill
import 'whatwg-fetch';
// Or provide custom fetch implementation
import { DI } from '@aurelia/kernel';
import { IFetchFn } from '@aurelia/fetch-client';
DI.getGlobalContainer().register(
Registration.instance(IFetchFn, myCustomFetchImplementation)
);
// Wrong - returning wrong type
this.http.configure(config => {
return 'invalid'; // ❌ Returns string instead of configuration
});
// Correct - return configuration or void
this.http.configure(config => {
config.withBaseUrl('https://api.example.com');
return config; // ✅ Return the configuration object
});
// Also correct - no return (void)
this.http.configure(config => {
config.withBaseUrl('https://api.example.com');
// ✅ Void return is fine
});
// Wrong - retry not last
this.http.configure(config => config
.withRetry({ maxRetries: 3 }) // ❌ Not last
.withInterceptor(loggingInterceptor) // This comes after retry
);
// Correct - retry is last
this.http.configure(config => config
.withInterceptor(loggingInterceptor)
.withRetry({ maxRetries: 3 }) // ✅ Last interceptor
);
export class AutoRefreshExample {
private http = resolve(IHttpClient);
private cacheService = resolve(ICacheService);
constructor() {
const cacheInterceptor = new CacheInterceptor({
cacheTime: 300_000, // 5 minutes total cache time
staleTime: 60_000, // 1 minute until stale
refreshStaleImmediate: true // Auto-refresh when stale
});
this.http.configure(config => config.withInterceptor(cacheInterceptor));
// Monitor refresh events
this.cacheService.subscribe(CacheEvent.CacheStaleRefreshed, (data) => {
console.log('Cache automatically refreshed:', data.key);
});
}
async getData() {
// First call: fetches from server, caches for 5 min, sets 1 min stale timer
const data1 = await this.http.get('/api/data');
// Calls within 1 minute: served from cache
const data2 = await this.http.get('/api/data');
// After 1 minute: cache automatically refreshed in background
// After refresh: new 5 min cache, new 1 min stale timer set
return data1;
}
}