JAVASCRIPT
Implement In-Memory Caching for External API Responses
Boost performance and reduce API call volume by implementing a simple in-memory cache for external API responses in a Node.js application, improving efficiency and responsiveness.
const NodeCache = require('node-cache'); // npm install node-cache
const myCache = new NodeCache({ stdTTL: 300, checkperiod: 120 }); // Cache items for 5 minutes (300 seconds)
async function getCachedApiResponse(cacheKey, apiUrl, fetchOptions = {}) {
// Try to retrieve data from cache
const cachedData = myCache.get(cacheKey);
if (cachedData) {
console.log(`Cache hit for key: ${cacheKey}`);
return cachedData;
}
console.log(`Cache miss for key: ${cacheKey}. Fetching from API...`);
try {
const response = await fetch(apiUrl, fetchOptions);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Store data in cache
myCache.set(cacheKey, data);
console.log(`Data for key: ${cacheKey} cached.`);
return data;
} catch (error) {
console.error(`Error fetching or parsing data from ${apiUrl}:`, error);
throw error;
}
}
// Example Usage in an Express route or service:
// const express = require('express');
// const app = express();
// const PORT = 3000;
// app.get('/products', async (req, res) => {
// try {
// // Use a unique cache key for this request, e.g., based on URL or query params
// const products = await getCachedApiResponse('all_products', 'https://api.example.com/products');
// res.json(products);
// } catch (error) {
// res.status(500).json({ message: 'Failed to retrieve products', error: error.message });
// }
// });
// app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
How it works: This JavaScript snippet demonstrates how to implement a simple in-memory cache for external API responses using the `node-cache` library. The `getCachedApiResponse` function first checks if data for a given `cacheKey` exists in the cache. If found, it returns the cached data immediately. Otherwise, it makes the API call, stores the fetched data in the cache with a specified time-to-live (TTL), and then returns it. This approach significantly reduces redundant API calls, lowers latency, and improves the overall performance and efficiency of your application.