Because route-caching of simple data/responses should ALSO be simple.
npm install apicache
To use, simply inject the middleware (example:
apicache.middleware('5 minutes', [optionalMiddlewareToggle])) into your routes. Everything else is automagic.
let app =let cache = apicachemiddlewareapp
let cache = apicachemiddlewareappapp
let app =// if redisClient option is defined, apicache will use redis client// instead of built-in memory storelet cacheWithRedis = apicacheoptions redisClient: redismiddlewareapp
let cache = apicachemiddlewareapp// routes are automatically added to index, but may be further added// to groups for quick deleting of collectionsapp// add route to display cache indexapp// add route to manually clear target/groupapp/*GET /api/foo/bar --> caches entry at /api/foo/bar and adds a group called 'foo' to indexGET /api/cache/index --> displays indexGET /api/cache/clear/foo --> clears all cached entries for 'foo' group/collection*/
// higher-order function returns false for responses of other status codes (e.g. 403, 404, 500, etc)const onlyStatus200 = resstatusCode === 200const cacheSuccesses =appapp
let cache = apicacheoptionsheaders:'cache-control': 'no-cache'middlewarelet cache5min = // continue to use normally
apicache.options([globalOptions])- getter/setter for global options. If used as a setter, this function is chainable, allowing you to do things such as... say... return the middleware.
apicache.middleware([duration], [toggleMiddleware], [localOptions])- the actual middleware that will be used in your routes.
durationis in the following format "[length] [unit]", as in
"1 day". A second param is a middleware toggle function, accepting request and response params, and must return truthy to enable cache for the request. Third param is the options that will override global ones and affect this middleware only.
middleware.options([localOptions])- getter/setter for middleware-specific options that will override global ones.
apicache.getIndex()- returns current cache index [of keys]
apicache.clear([target])- clears cache target (key or group), or entire cache if no value passed, returns new index.
apicache.newInstance([options])- used to create a new ApiCache instance (by default, simply requiring this library shares a common instance)
apicache.clone()- used to create a new ApiCache instance with the same options as the current one
debug: false|true // if true, enables console outputdefaultDuration: '1 hour' // should be either a number (in ms) or a string, defaults to 1 hourenabled: true|false // if false, turns off caching globally (useful on dev)redisClient: client // if provided, uses the [node-redis]() client instead of [memory-cache]()appendKey: // appendKey takes the req/res objects and returns a custom value to extend the cache keyheaderBlacklist: // list of headers that should never be cachedstatusCodes:exclude: // list status codes to specifically exclude (e.g. [404, 403] cache all responses unless they had a 404 or 403 status)include: // list status codes to require (e.g.  caches ONLY responses with a success/200 code)headers:// 'cache-control': 'no-cache' // example of header overwrite
Sometimes you need custom keys (e.g. save routes per-session, or per method). We've made it easy!
Note: All req/res attributes used in the generation of the key must have been set previously (upstream). The entire route logic block is skipped on future cache hits so it can't rely on those params.
apicacheoptionsreqmethod + ressessionid
Oftentimes it benefits us to group cache entries, for example, by collection (in an API). This
would enable us to clear all cached "post" requests if we updated something in the "post" collection
for instance. Adding a simple
req.apicacheGroup = [somevalue]; to your route enables this. See example below:
var apicache =var cache = apicachemiddleware// GET collection/idapp;// POST collection/idapp;
Additionally, you could add manual cache control to the previous project with routes such as these:
// GET apicache index (for the curious)app;// GET apicache index (for the curious)app;
$ export DEBUG=apicache $ export DEBUG=apicache,othermoduleThatDebugModuleWillPickUp,etc
apicacheoptions debug: true
GET routes between admin and public sites, you'll likely want the
routes to be cached from your public client, but NOT cached when from the admin client. This
is achieved by sending a
"x-apicache-bypass": true header along with the requst from the admin.
The presence of this header flag will bypass the cache, ensuring you aren't looking at stale data.
Special thanks to all those that use this library and report issues, but especially to the following active users that have helped add to the core functionality!