JAVASCRIPT

Simple In-Memory Caching for REST API Responses

Optimize web application performance by implementing a basic in-memory cache to store and retrieve API responses, reducing redundant network requests and improving load times.

const apiCache = new Map();

async function fetchWithCache(url, options = {}, ttl = 60000) {
  const now = Date.now();
  const cached = apiCache.get(url);

  if (cached && (now - cached.timestamp < ttl)) {
    console.log(`Cache hit for ${url}`);
    return cached.data;
  }

  console.log(`Cache miss for ${url}, fetching...`);
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    apiCache.set(url, { data, timestamp: now });
    return data;
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
}

// Example usage:
// fetchWithCache('https://api.example.com/data', {}, 30000) // Cache for 30 seconds
//   .then(data => console.log('Fetched Data:', data))
//   .catch(error => console.error('Error fetching data:', error));
How it works: This JavaScript snippet implements a basic in-memory cache for API responses using a `Map`. The `fetchWithCache` function checks if a response for a given URL exists in the cache and is still valid based on its Time-To-Live (TTL). If cached and valid, it returns the cached data instantly. Otherwise, it makes a new fetch request, stores the successful response with a timestamp, and then returns the data. This helps reduce redundant API calls and improves application responsiveness by serving data from memory.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs