derekvmcintire / acs-next-api

0 stars 0 forks source link

Add Cache #66

Open derekvmcintire opened 3 days ago

derekvmcintire commented 3 days ago

1. Identify Caching Requirements

2. Choose a Caching Layer

3. Cache Query Results

4. Implementing Pagination with Cached Data

5. Example with in-memory cache

sing an in-memory cache in Node.js can be quite simple and is useful for caching data temporarily within the same server instance. Here’s how you can use an in-memory cache with the node-cache library, which is lightweight and provides basic caching functionalities like setting a TTL (time-to-live) for each cache item.

1. Install node-cache

npm install node-cache

2. Set Up the Cache

Initialize node-cache in your API, typically in a separate module so you can reuse it across various parts of your app.

// cache.js
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 3600, checkperiod: 120 }); // TTL: 1 hour, check every 2 minutes

module.exports = cache;

In this setup:

3. Use the Cache in an API Route

Here’s an example of how you might use node-cache in a route that fetches rider rankings. It will check if the rankings are cached, and if not, it will query the database, cache the results, and return them.

// ridersController.js
const cache = require('./cache');

// Mock function that simulates an expensive database query
async function fetchAndCalculateRankingsFromDatabase(year, sort) {
  // Simulate data retrieval and sorting...
  return [
    { id: 1, name: 'Rider 1', points: 120 },
    { id: 2, name: 'Rider 2', points: 110 },
    // Assume more data here...
  ];
}

async function getRiderRankings(req, res) {
  const { year, limit = 5, page = 1, sort = 'points' } = req.query;
  const cacheKey = `rankings:${year}:${sort}`;

  // Check if rankings are in cache
  let rankings = cache.get(cacheKey);

  if (!rankings) {
    // If not cached, fetch from database and process the data
    rankings = await fetchAndCalculateRankingsFromDatabase(year, sort);

    // Cache the processed data
    cache.set(cacheKey, rankings);
  }

  // Paginate the cached data
  const startIndex = (page - 1) * limit;
  const endIndex = startIndex + limit;
  const paginatedRankings = rankings.slice(startIndex, endIndex);

  res.json(paginatedRankings);
}

Explanation

Additional Cache Management Methods node-cache provides additional methods that can help manage your cache:

Example for Clearing Cache on Data Updates

If rankings are recalculated or updated, you’ll want to clear the relevant cache. Here’s an example of how you might do this in an update function:

async function updateRiderRankings(newRankingsData) {
  // Update rankings data in the database...

  // Invalidate cache for any rankings that may be affected
  cache.del(`rankings:2024:points`); // Adjust key as needed
}