JAVASCRIPT
Cache API Responses with a Time-to-Live (TTL)
Implement a simple in-memory cache with a time-to-live (TTL) for API responses in JavaScript, reducing redundant network requests and improving performance.
const axios = require('axios');
const apiCache = new Map(); // Stores { url: { data, timestamp, ttl } }
/**
* Fetches data from an API, caching the response for a specified TTL.
* @param {string} url The API endpoint URL.
* @param {number} ttlSeconds Time-to-live for the cache entry in seconds.
* @returns {Promise<any>} The API response data.
*/
async function fetchWithCache(url, ttlSeconds = 60) {
const now = Date.now();
const cachedEntry = apiCache.get(url);
if (cachedEntry && (now - cachedEntry.timestamp) < (cachedEntry.ttl * 1000)) {
console.log(`Cache hit for ${url}`);
return cachedEntry.data;
}
console.log(`Cache miss for ${url}. Fetching from API...`);
try {
const response = await axios.get(url);
const data = response.data;
apiCache.set(url, { data, timestamp: now, ttl: ttlSeconds });
return data;
} catch (error) {
console.error(`Error fetching ${url}:`, error.message);
throw error;
}
}
// --- Example Usage ---
(async () => {
const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/todos/1';
console.log('--- First call (cache miss) ---');
let data1 = await fetchWithCache(API_ENDPOINT, 5); // Cache for 5 seconds
console.log('Data 1:', data1.title);
console.log('
--- Second call (cache hit) ---');
let data2 = await fetchWithCache(API_ENDPOINT, 5);
console.log('Data 2:', data2.title);
console.log('
--- Waiting for cache to expire ---');
await new Promise(resolve => setTimeout(resolve, 6000)); // Wait 6 seconds
console.log('
--- Third call (cache miss after expiration) ---');
let data3 = await fetchWithCache(API_ENDPOINT, 5);
console.log('Data 3:', data3.title);
console.log('
--- Another endpoint with different TTL ---');
const ANOTHER_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1';
let data4 = await fetchWithCache(ANOTHER_ENDPOINT, 2); // Cache for 2 seconds
console.log('Data 4:', data4.title);
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('
--- Cache hit for another endpoint ---');
let data5 = await fetchWithCache(ANOTHER_ENDPOINT, 2);
console.log('Data 5:', data5.title);
})();
How it works: This JavaScript snippet demonstrates implementing a simple in-memory cache for API responses using a `Map` object. The `fetchWithCache` function checks if a requested URL's data exists in the cache and is still valid (within its Time-to-Live or TTL). If valid, it returns the cached data instantly; otherwise, it fetches the data from the API, stores it in the cache with the current timestamp, and then returns it. This technique reduces redundant API calls, lowers server load, and significantly improves the response time for frequently requested data.