apicache

repository·master·Indexed 23 days ago

https://github.com/kwhitley/apicache

An ultra-simplified API response caching middleware for Express/Node.js (v1.6.3) that supports plain-English durations (e.g., '5 minutes', '1 hour'). It features an in-memory engine with optional Redis support, global and route-specific configuration, cache grouping for bulk clearing, and performance tracking via apicache.getPerformance().

Tokens
3.3K
Snippets
7
Records
20
Agent score
29%

What's inside apicache

  1. Group cache entries for bulk clearing

    master

    You can group cache entries by assigning a value to req.apicacheGroup within your route handler. This allows you to clear an entire collection of cached items at once using apicache.clear(groupName).

    import apicache from 'apicache'
    let cache = apicache.middleware
    
    app.use(cache('5 minutes'))
    
    // routes are automatically added to index, but may be further added
    // to groups for quick deleting of collections
    app.get('/api/:collection/:item?', (req, res) => {
      req.apicacheGroup = req.params.collection
      res.json({ success: true })
    })
    
    // To clear the group later:
    // apicache.clear('collection_name')
  2. Configure cache-control behavior with respectCacheControl

    master
    In version v1.6.0, the respectCacheControl option was added. When enabled, the middleware will honor no-cache directives, ensuring that the cache respects standard HTTP cache-control headers.
  3. How cache keys are generated

    master

    By default, apicache uses the request URL (req.originalUrl or req.url) as the cache key. You can customize this behavior using the appendKey option.

    Append Key Modes:

    1. Function: A function (req, res) => string that returns a string to be appended to the key.
    2. Path Array: An array of strings representing paths through the req object. For example, ['headers', 'user-agent'] will append the value of req.headers['user-agent'] to the key.

    If jsonp: true is enabled, the query string is stripped from the key.

  4. Enable or disable performance tracking

    master
    The trackPerformance option allows you to toggle the internal performance tracking system. As of v1.5.2, this is set to false by default. You can enable it to gather metrics via apicache.getPerformance().
  5. Install and use apicache in Express

    master

    To use apicache as middleware in an Express application, require the module and use the .middleware() method. You can specify a duration using plain-English strings (e.g., '5 minutes', '1 hour') or milliseconds.

    const express = require('express');
    const apicache = require('apicache');
    const app = express();
    
    // Cache responses for 5 minutes
    app.use(apicache.middleware('5 minutes'));
    
    app.get('/data', (req, res) => {
      res.json({ message: 'This is cached data' });
    });
    
    app.listen(3000);
  6. Cache all routes globally

    master

    You can apply caching to every route in your application by using app.use() with the apicache.middleware.

    let cache = apicache.middleware
    
    app.use(cache('5 minutes'))
    
    app.get('/will-be-cached', (req, res) => {
      res.json({ success: true })
    })
  7. Use a middleware toggle for fine-grained control

    master

    You can pass a second argument to apicache.middleware which acts as a toggle function. This function receives (req, res) and must return a truthy value to enable caching for that specific request. This is useful for only caching successful responses (e.g., status 200).

    // 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('/api/missing', cacheSuccesses, (req, res) => {
      res.status(404).json({ results: 'will not be cached' 
    })
    })
    
    app.get('/api/found', cacheSuccesses, (req, res) => {
      res.json({ results: 'will be cached' })
    })
  8. Configure apicache to use Redis

    master

    By default, apicache uses an in-memory engine. To use Redis, provide a redisClient (compatible with node-redis) via apicache.options().

    import express from 'express'
    import apicache from 'apicache'
    import redis from 'redis'
    
    let app = express()
    
    // if redisClient option is defined, apicache will use redis client
    // instead of built-in memory store
    let cacheWithRedis = apicache.options({ redisClient: redis.createClient() }).middleware
    
    app.get('/will-be-cached', cacheWithRedis('5 minutes'), (req, res) => {
      res.json({ success: true })
    })
  9. Cache specific Express routes

    master

    To cache a specific route, inject apicache.middleware into your route definition. The first argument to the middleware is a plain-English duration string (e.g., '5 minutes', '1 hour', '1 day').

    import express from 'express'
    import apicache from 'apicache'
    
    let app = express()
    let cache = apicache.middleware
    
    app.get('/api/collection/:id?', cache('5 minutes'), (req, res) => {
      // do some work... this will only occur once per 5 minutes
      res.json({ foo: 'bar' })
    })
  10. Monitor cache performance with apicache.getPerformance()

    master
    Starting from version v1.5.0, you can use apicache.getPerformance() to retrieve cache metrics on a per-route basis. This is useful for monitoring the effectiveness of your caching strategy and identifying routes that benefit most from the middleware.