JAVASCRIPT
Server-Side Caching for External API Responses in Node.js
Implement an efficient in-memory server-side cache in Node.js to store external API responses, reducing redundant calls and improving application performance.
// A simple in-memory cache for demonstration.
// For production, consider Redis or Memcached for persistence and scalability.
const cache = new Map();
// Cache entry structure: { data: '...', timestamp: Date.now(), expiresAt: Date.now() + ttl }
const CACHE_TTL_SECONDS = 300; // 5 minutes (300 seconds)
async function fetchAndCacheData(key, fetcherFunction, ttlSeconds = CACHE_TTL_SECONDS) {
const cachedItem = cache.get(key);
if (cachedItem && Date.now() < cachedItem.expiresAt) {
console.log(`Cache hit for key: ${key}`);
return cachedItem.data;
}
console.log(`Cache miss for key: ${key}, fetching new data...`);
const newData = await fetcherFunction();
cache.set(key, {
data: newData,
timestamp: Date.now(),
expiresAt: Date.now() + (ttlSeconds * 1000)
});
return newData;
}
// Example API fetcher function (simulated)
async function getExternalUserData(userId) {
// Simulate network delay
await new Promise(resolve => setTimeout(Math.random() * 1000 + 500, resolve));
console.log(`Fetching data for user ${userId} from external API...`);
return {
id: userId,
name: `User ${userId} Name`,
email: `user${userId}@example.com`,
source: 'external-api'
};
}
// Usage example:
(async () => {
console.log('--- First call (cache miss) ---');
let userData = await fetchAndCacheData('user_123', () => getExternalUserData(123));
console.log('User Data:', userData);
console.log('
--- Second call immediately (cache hit) ---');
userData = await fetchAndCacheData('user_123', () => getExternalUserData(123));
console.log('User Data:', userData);
console.log('
--- Call for a different user (cache miss) ---');
userData = await fetchAndCacheData('user_456', () => getExternalUserData(456));
console.log('User Data:', userData);
// Simulate waiting for cache to expire
console.log(`
--- Waiting for ${CACHE_TTL_SECONDS + 1} seconds for cache to expire... ---`);
await new Promise(resolve => setTimeout((CACHE_TTL_SECONDS + 1) * 1000, resolve));
console.log('
--- Third call after cache expiry (cache miss) ---');
userData = await fetchAndCacheData('user_123', () => getExternalUserData(123));
console.log('User Data:', userData);
})();
How it works: This snippet demonstrates a basic server-side in-memory caching mechanism for external API responses in Node.js. The `fetchAndCacheData` function first checks if the requested data (`key`) exists in the cache and if it hasn't expired. If a valid cached item is found (cache hit), it's returned immediately. Otherwise (cache miss), the provided `fetcherFunction` is executed to retrieve fresh data, which is then stored in the cache with an expiration timestamp before being returned. This approach significantly reduces the number of calls to external APIs, improving application performance and potentially avoiding rate limits. For production environments, a more robust solution like Redis or Memcached is recommended.