Caching Strategies
Optimize performance with intelligent caching.
Overview
The DotPassport SDK does not include built-in caching - this allows you to implement caching strategies that best fit your application's needs. This guide shows common patterns for caching API responses.
API Client Caching
Basic In-Memory Cache
import { DotPassportClient } from '@dotpassport/sdk';
class CachedDotPassportClient {
private client: DotPassportClient;
private cache = new Map<string, { data: any; timestamp: number }>();
private defaultTTL = 5 * 60 * 1000; // 5 minutes
constructor(apiKey: string) {
this.client = new DotPassportClient({ apiKey });
}
private getCacheKey(method: string, address: string): string {
return `${method}:${address}`;
}
private isValid(timestamp: number, ttl: number): boolean {
return Date.now() - timestamp < ttl;
}
async getScores(address: string, ttl = this.defaultTTL) {
const key = this.getCacheKey('scores', address);
const cached = this.cache.get(key);
if (cached && this.isValid(cached.timestamp, ttl)) {
return cached.data;
}
const data = await this.client.getScores(address);
this.cache.set(key, { data, timestamp: Date.now() });
return data;
}
async getBadges(address: string, ttl = this.defaultTTL) {
const key = this.getCacheKey('badges', address);
const cached = this.cache.get(key);
if (cached && this.isValid(cached.timestamp, ttl)) {
return cached.data;
}
const data = await this.client.getBadges(address);
this.cache.set(key, { data, timestamp: Date.now() });
return data;
}
clearCache(address?: string) {
if (address) {
// Clear specific address
for (const key of this.cache.keys()) {
if (key.includes(address)) {
this.cache.delete(key);
}
}
} else {
// Clear all
this.cache.clear();
}
}
}localStorage Cache
For persistent caching across sessions:
React Cache Hook
Stale-While-Revalidate Pattern
Return cached data immediately while fetching fresh data:
Cache Invalidation
Time-Based Expiration
Manual Invalidation
Best Practices
Choose appropriate TTL values - Balance freshness vs. performance
Cache at the right level - API responses, not derived data
Handle cache misses gracefully - Always have a fallback to fetch
Clear cache on relevant user actions - Keep data consistent
Use SWR for better UX - Show stale data while loading fresh
Related
Last updated
