api-cache.ts

import * as apicache from 'apicache';
import { apiPrefix } from '../../utility/constants/app';

export default async function apiCacheEndpoints(app) {
  const cache = apicache.middleware;

  // higher-order function returns false for responses of other status codes (e.g. 403, 404, 500, etc)
  const onlyStatus200 = (req, res) => res.statusCode === 200;

  const cacheSuccesses = cache('5 minutes', onlyStatus200);

  app.get(`${apiPrefix}/cache/missing`, cacheSuccesses, (req, res) => {
    res.status(404).json({ results: 'will not be cached' });
  });

  app.get(`${apiPrefix}/cache/found`, cacheSuccesses, (req, res) => {
    res.json({ results: 'will be cached' });
  });

  // add route to display cache performance (courtesy of @killdash9)
  app.get(`${apiPrefix}/cache/performance`, (req, res) => {
    res.json(apicache.getPerformance());
  });

  // add route to display cache index
  app.get(`${apiPrefix}/cache/index`, (req, res) => {
    res.json(apicache.getIndex());
  });

  // add route to manually clear target/group
  app.get(`${apiPrefix}/cache/clear/:target?`, (req, res) => {
    res.json(apicache.clear(req.params.target));
  });
}