Gathering detailed insights and metrics for apicache-extra
Gathering detailed insights and metrics for apicache-extra
Gathering detailed insights and metrics for apicache-extra
Gathering detailed insights and metrics for apicache-extra
npm install apicache-extra
Typescript
Module System
Min. Node Version
Node Version
NPM Version
74.5
Supply Chain
99
Quality
79.6
Maintenance
100
Vulnerability
100
License
JavaScript (100%)
Total Downloads
14,970
Last Day
1
Last Week
163
Last Month
585
Last Year
8,565
MIT License
1 Stars
404 Commits
15 Branches
1 Contributors
Updated on Oct 30, 2024
Minified
Minified + Gzipped
Latest Version
1.10.2
Package Id
apicache-extra@1.10.2
Unpacked Size
89.95 kB
Size
20.24 kB
File Count
18
NPM Version
6.14.18
Node Version
14.21.3
Published on
Oct 30, 2024
Cumulative downloads
Total Downloads
Because route-caching of simple data/responses should ALSO be simple.
To use, simply inject the middleware (example: apicache.middleware('5 minutes', [optionalMiddlewareToggle])
) into your routes. Everything else is automagic.
1import express from 'express' 2import apicache from 'apicache' 3 4let app = express() 5let cache = apicache.middleware 6 7app.get('/api/collection/:id?', cache('5 minutes'), (req, res) => { 8 // do some work... this will only occur once per 5 minutes 9 res.json({ foo: 'bar' }) 10})
1let cache = apicache.middleware 2 3app.use(cache('5 minutes')) 4 5app.get('/will-be-cached', (req, res) => { 6 res.json({ success: true }) 7})
1import express from 'express' 2import apicache from 'apicache' 3import redis from 'redis' 4 5let app = express() 6 7// if redisClient option is defined, apicache will use redis client 8// instead of built-in memory store 9let cacheWithRedis = apicache.options({ redisClient: redis.createClient() }).middleware 10 11app.get('/will-be-cached', cacheWithRedis('5 minutes'), (req, res) => { 12 res.json({ success: true }) 13})
1import apicache from 'apicache' 2let cache = apicache.middleware 3 4app.use(cache('5 minutes')) 5 6// routes are automatically added to index, but may be further added 7// to groups for quick deleting of collections 8app.get('/api/:collection/:item?', (req, res) => { 9 req.apicacheGroup = req.params.collection 10 res.json({ success: true }) 11}) 12 13// add route to display cache performance (courtesy of @killdash9) 14app.get('/api/cache/performance', (req, res) => { 15 res.json(apicache.getPerformance()) 16}) 17 18// add route to display cache index 19app.get('/api/cache/index', (req, res) => { 20 res.json(apicache.getIndex()) 21}) 22 23// add route to manually clear target/group 24app.get('/api/cache/clear/:target?', (req, res) => { 25 res.json(apicache.clear(req.params.target)) 26}) 27 28/* 29 30GET /api/foo/bar --> caches entry at /api/foo/bar and adds a group called 'foo' to index 31GET /api/cache/index --> displays index 32GET /api/cache/clear/foo --> clears all cached entries for 'foo' group/collection 33 34*/
1// higher-order function returns false for responses of other status codes (e.g. 403, 404, 500, etc) 2const onlyStatus200 = (req, res) => res.statusCode === 200 3 4const cacheSuccesses = cache('5 minutes', onlyStatus200) 5 6app.get('/api/missing', cacheSuccesses, (req, res) => { 7 res.status(404).json({ results: 'will not be cached' }) 8}) 9 10app.get('/api/found', cacheSuccesses, (req, res) => { 11 res.json({ results: 'will be cached' }) 12})
1let cache = apicache.options({ 2 headers: { 3 'cache-control': 'no-cache', 4 }, 5}).middleware 6 7let cache5min = cache('5 minute') // 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. duration
is in the following format "[length][unit]", as in "10 minutes"
or "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.getPerformance()
- returns current cache performance (cache hit rate)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 one1{ 2 debug: false|true, // if true, enables console output 3 defaultDuration: '1 hour', // should be either a number (in ms) or a string, defaults to 1 hour 4 enabled: true|false, // if false, turns off caching globally (useful on dev) 5 redisClient: client, // if provided, uses the [node-redis](https://github.com/NodeRedis/node_redis) client instead of [memory-cache](https://github.com/ptarjan/node-cache) 6 appendKey: fn(req, res), // appendKey takes the req/res objects and returns a custom value to extend the cache key 7 headerBlacklist: [], // list of headers that should never be cached 8 cacheRouteList:[], // list of route will be cached 9 method:{ 10 include: [], // list of method will be cached (e.g. ["GET"]) 11 exclude:[] // list of method will be excluded (e.g. ["POST","PUT","DELETE"]) 12 }, 13 statusCodes: { 14 exclude: [], // list status codes to specifically exclude (e.g. [404, 403] cache all responses unless they had a 404 or 403 status) 15 include: [], // list status codes to require (e.g. [200] caches ONLY responses with a success/200 code) 16 }, 17 trackPerformance: false, // enable/disable performance tracking... WARNING: super cool feature, but may cause memory overhead issues 18 headers: { 19 // 'cache-control': 'no-cache' // example of header overwrite 20 }, 21 respectCacheControl: false|true // If true, 'Cache-Control: no-cache' in the request header will bypass the cache. 22}
1$ npm install -D @types/apicache
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.
1apicache.options({ 2 appendKey: (req, res) => req.method + res.session.id, 3})
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:
1var apicache = require('apicache') 2var cache = apicache.middleware 3 4// GET collection/id 5app.get('/api/:collection/:id?', cache('1 hour'), function(req, res, next) { 6 req.apicacheGroup = req.params.collection 7 // do some work 8 res.send({ foo: 'bar' }) 9}) 10 11// POST collection/id 12app.post('/api/:collection/:id?', function(req, res, next) { 13 // update model 14 apicache.clear(req.params.collection) 15 res.send('added a new item, so the cache has been cleared') 16})
Additionally, you could add manual cache control to the previous project with routes such as these:
1// GET apicache index (for the curious) 2app.get('/api/cache/index', function(req, res, next) { 3 res.send(apicache.getIndex()) 4}) 5 6// GET apicache index (for the curious) 7app.get('/api/cache/clear/:key?', function(req, res, next) { 8 res.send(200, apicache.clear(req.params.key || req.query.key)) 9})
$ export DEBUG=apicache
$ export DEBUG=apicache,othermoduleThatDebugModuleWillPickUp,etc
1import apicache from 'apicache' 2 3apicache.options({ debug: true })
When sharing 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!
No vulnerabilities found.
No security vulnerabilities found.
Last Day
-50%
1
Compared to previous day
Last Week
-3.6%
163
Compared to previous week
Last Month
8.9%
585
Compared to previous month
Last Year
68.9%
8,565
Compared to previous year