UNPKG

15.4 kBMarkdownView Raw
1# A simple API response caching middleware for Express/Node using plain-english durations.
2
3#### Supports Redis or built-in memory engine with auto-clearing.
4
5[![npm version](https://badge.fury.io/js/apicache.svg)](https://www.npmjs.com/package/apicache)
6[![node version support](https://img.shields.io/node/v/apicache.svg)](https://www.npmjs.com/package/apicache)
7[![Build Status via Travis CI](https://travis-ci.org/kwhitley/apicache.svg?branch=master)](https://travis-ci.org/kwhitley/apicache)
8[![Coverage Status](https://coveralls.io/repos/github/kwhitley/apicache/badge.svg?branch=master)](https://coveralls.io/github/kwhitley/apicache?branch=master)
9[![NPM downloads](https://img.shields.io/npm/dt/apicache.svg?style=flat-square)](https://www.npmjs.com/package/apicache)
10
11## Why?
12
13Because route-caching of simple data/responses should ALSO be simple.
14
15## Usage
16
17To use, simply inject the middleware (example: `apicache.middleware('5 minutes', [optionalMiddlewareToggle])`) into your routes. Everything else is automagic.
18
19#### Cache a route
20
21```js
22import express from 'express'
23import apicache from 'apicache'
24
25let app = express()
26let cache = apicache.middleware
27
28app.get('/api/collection/:id?', cache('5 minutes'), (req, res) => {
29 // do some work... this will only occur once per 5 minutes
30 res.json({ foo: 'bar' })
31})
32```
33
34#### Cache all routes
35
36```js
37let cache = apicache.middleware
38
39app.use(cache('5 minutes'))
40
41app.get('/will-be-cached', (req, res) => {
42 res.json({ success: true })
43})
44```
45
46#### Use with Redis
47
48```js
49import express from 'express'
50import apicache from 'apicache'
51import redis from 'redis'
52
53let app = express()
54
55// if redisClient option is defined, apicache will use redis client
56// instead of built-in memory store
57let cacheWithRedis = apicache.options({ redisClient: redis.createClient() }).middleware
58
59app.get('/will-be-cached', cacheWithRedis('5 minutes'), (req, res) => {
60 res.json({ success: true })
61})
62```
63
64#### Cache grouping and manual controls
65
66```js
67import apicache from 'apicache'
68let cache = apicache.middleware
69
70app.use(cache('5 minutes'))
71
72// routes are automatically added to index, but may be further added
73// to groups for quick deleting of collections
74app.get('/api/:collection/:item?', (req, res) => {
75 req.apicacheGroup = req.params.collection
76 res.json({ success: true })
77})
78
79// add route to display cache performance (courtesy of @killdash9)
80app.get('/api/cache/performance', (req, res) => {
81 res.json(apicache.getPerformance())
82})
83
84// add route to display cache index
85app.get('/api/cache/index', (req, res) => {
86 res.json(apicache.getIndex())
87})
88
89// add route to manually clear target/group
90app.get('/api/cache/clear/:target?', (req, res) => {
91 res.json(apicache.clear(req.params.target))
92})
93
94/*
95
96GET /api/foo/bar --> caches entry at /api/foo/bar and adds a group called 'foo' to index
97GET /api/cache/index --> displays index
98GET /api/cache/clear/foo --> clears all cached entries for 'foo' group/collection
99
100*/
101```
102
103#### Use with middleware toggle for fine control
104
105```js
106// higher-order function returns false for responses of other status codes (e.g. 403, 404, 500, etc)
107const onlyStatus200 = (req, res) => res.statusCode === 200
108
109const cacheSuccesses = cache('5 minutes', onlyStatus200)
110
111app.get('/api/missing', cacheSuccesses, (req, res) => {
112 res.status(404).json({ results: 'will not be cached' })
113})
114
115app.get('/api/found', cacheSuccesses, (req, res) => {
116 res.json({ results: 'will be cached' })
117})
118```
119
120#### Prevent cache-control header "max-age" from automatically being set to expiration age
121
122```js
123let cache = apicache.options({
124 headers: {
125 'cache-control': 'no-cache',
126 },
127}).middleware
128
129let cache5min = cache('5 min') // continue to use normally
130```
131
132## API
133
134- `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.
135- `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.
136- `middleware.options([localOptions])` - getter/setter for middleware-specific options that will override global ones.
137- `apicache.getPerformance()` - returns current cache performance (cache hit rate)
138- `apicache.getIndex()` - returns current cache index [of keys]
139- `apicache.clear([target])` - clears cache target (key or group), or entire cache if no value passed, returns new index.
140- `apicache.newInstance([options])` - used to create a new ApiCache instance (by default, simply requiring this library shares a common instance)
141- `apicache.clone()` - used to create a new ApiCache instance with the same options as the current one
142
143#### Available Options (first value is default)
144
145```js
146{
147 debug: false|true, // if true, enables console output
148 defaultDuration: '1 hour', // should be either a number (in ms) or a string, defaults to 1 hour
149 enabled: true|false, // if false, turns off caching globally (useful on dev)
150 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)
151 appendKey: fn(req, res), // appendKey takes the req/res objects and returns a custom value to extend the cache key
152 headerBlacklist: [], // list of headers that should never be cached
153 statusCodes: {
154 exclude: [], // list status codes to specifically exclude (e.g. [404, 403] cache all responses unless they had a 404 or 403 status)
155 include: [], // list status codes to require (e.g. [200] caches ONLY responses with a success/200 code)
156 },
157 trackPerformance: false, // enable/disable performance tracking... WARNING: super cool feature, but may cause memory overhead issues
158 headers: {
159 // 'cache-control': 'no-cache' // example of header overwrite
160 },
161 respectCacheControl: false|true // If true, 'Cache-Control: no-cache' in the request header will bypass the cache.
162}
163```
164
165##### \*Optional: Typescript Types (courtesy of [@danielsogl](https://github.com/danielsogl))
166
167```bash
168$ npm install -D @types/apicache
169```
170
171## Custom Cache Keys
172
173Sometimes you need custom keys (e.g. save routes per-session, or per method).
174We've made it easy!
175
176**Note:** All req/res attributes used in the generation of the key must have been set
177previously (upstream). The entire route logic block is skipped on future cache hits
178so it can't rely on those params.
179
180```js
181apicache.options({
182 appendKey: (req, res) => req.method + res.session.id,
183})
184```
185
186## Cache Key Groups
187
188Oftentimes it benefits us to group cache entries, for example, by collection (in an API). This
189would enable us to clear all cached "post" requests if we updated something in the "post" collection
190for instance. Adding a simple `req.apicacheGroup = [somevalue];` to your route enables this. See example below:
191
192```js
193var apicache = require('apicache')
194var cache = apicache.middleware
195
196// GET collection/id
197app.get('/api/:collection/:id?', cache('1 hour'), function(req, res, next) {
198 req.apicacheGroup = req.params.collection
199 // do some work
200 res.send({ foo: 'bar' })
201})
202
203// POST collection/id
204app.post('/api/:collection/:id?', function(req, res, next) {
205 // update model
206 apicache.clear(req.params.collection)
207 res.send('added a new item, so the cache has been cleared')
208})
209```
210
211Additionally, you could add manual cache control to the previous project with routes such as these:
212
213```js
214// GET apicache index (for the curious)
215app.get('/api/cache/index', function(req, res, next) {
216 res.send(apicache.getIndex())
217})
218
219// GET apicache index (for the curious)
220app.get('/api/cache/clear/:key?', function(req, res, next) {
221 res.send(200, apicache.clear(req.params.key || req.query.key))
222})
223```
224
225## Debugging/Console Out
226
227#### Using Node environment variables (plays nicely with the hugely popular [debug](https://www.npmjs.com/package/debug) module)
228
229```
230$ export DEBUG=apicache
231$ export DEBUG=apicache,othermoduleThatDebugModuleWillPickUp,etc
232```
233
234#### By setting internal option
235
236```js
237import apicache from 'apicache'
238
239apicache.options({ debug: true })
240```
241
242## Client-Side Bypass
243
244When sharing `GET` routes between admin and public sites, you'll likely want the
245routes to be cached from your public client, but NOT cached when from the admin client. This
246is achieved by sending a `"x-apicache-bypass": true` header along with the requst from the admin.
247The presence of this header flag will bypass the cache, ensuring you aren't looking at stale data.
248
249## Contributors
250
251Special 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!
252
253- [@Chocobozzz](https://github.com/Chocobozzz) - the savior of getting this to pass all the Node 14/15 tests again... thanks for everyone's patience!!!
254- [@killdash9](https://github.com/killdash9) - restify support, performance/stats system, and too much else at this point to list
255- [@svozza](https://github.com/svozza) - added restify tests, test suite refactor, and fixed header issue with restify. Node v7 + Restify v5 conflict resolution, etag/if-none-match support, etcetc, etc. Triple thanks!!!
256- [@andredigenova](https://github.com/andredigenova) - Added header blacklist as options, correction to caching checks
257- [@peteboere](https://github.com/peteboere) - Node v7 headers update
258- [@rutgernation](https://github.com/rutgernation) - JSONP support
259- [@enricsangra](https://github.com/enricsangra) - added x-apicache-force-fetch header
260- [@tskillian](https://github.com/tskillian) - custom appendKey path support
261- [@agolden](https://github.com/agolden) - Content-Encoding preservation (for gzip, etc)
262- [@davidyang](https://github.com/davidyang) - express 4+ compatibility
263- [@nmors](https://github.com/nmors) - redis support
264- [@maytis](https://github.com/maytis), [@ashwinnaidu](https://github.com/ashwinnaidu) - redis expiration
265- [@ubergesundheit](https://github.com/ubergesundheit) - Corrected buffer accumulation using res.write with Buffers
266- [@danielsogl](https://github.com/danielsogl) - Keeping dev deps up to date, Typescript Types
267- [@vectart](https://github.com/vectart) - Added middleware local options support
268- [@davebaol](https://github.com/davebaol) - Added string support to defaultDuration option (previously just numeric ms)
269- [@Rauttis](https://github.com/rauttis) - Added ioredis support
270- [@fernandolguevara](https://github.com/fernandolguevara) - Added opt-out for performance tracking, great emergency fix, thank you!!
271
272### Bugfixes, tweaks, documentation, etc.
273
274- @Amhri, @Webcascade, @conmarap, @cjfurelid, @scambier, @lukechilds, @Red-Lv, @gesposito, @viebel, @RowanMeara, @GoingFast, @luin, @keithws, @daveross, @apascal, @guybrush
275
276### Changelog
277
278- **v1.6.0** - added respectCacheControl option flag to force honoring no-cache (thanks [@NaridaL](https://github.com/NaridaL)!)
279- **v1.5.4** - up to Node v15 support, HUGE thanks to [@Chocobozzz](https://github.com/Chocobozzz) and all the folks on the PR thread! <3
280- **v1.5.3** - multiple fixes: Redis should be connected before using (thanks @guybrush)
281- **v1.5.2** - multiple fixes: Buffer deprecation and \_headers deprecation, { trackPerformance: false } by default per discussion (sorry semver...)
282- **v1.5.1** - adds { trackPerformance } option to enable/disable performance tracking (thanks @fernandolguevara)
283- **v1.5.0** - exposes apicache.getPerformance() for per-route cache metrics (@killdash9 continues to deliver)
284- **v1.4.0** - cache-control header now auto-decrements in cached responses (thanks again, @killdash9)
285- **v1.3.0** - [securityfix] apicache headers no longer embedded in cached responses when NODE_ENV === 'production' (thanks for feedback @satya-jugran, @smddzcy, @adamelliotfields). Updated deps, now requiring Node v6.00+.
286- **v1.2.6** - middlewareToggle() now prevents response block on cache hit + falsy toggle (thanks @apascal)
287- **v1.2.5** - uses native Node setHeader() rather than express.js header() (thanks @keithws and @daveross)
288- **v1.2.4** - force content type to Buffer, using old and new Buffer creation syntax
289- **v1.2.3** - add etag to if-none-match 304 support (thanks for the test/issue @svozza)
290- **v1.2.2** - bugfix: ioredis.expire params (thanks @GoingFast and @luin)
291- **v1.2.1** - Updated deps
292- **v1.2.0** - Supports ioredis (thanks @Rauttis)
293- **v1.1.1** - bugfixes in expiration timeout clearing and content header preservation under compression (thanks @RowanMeara and @samimakicc).
294- **v1.1.0** - added the much-requested feature of a custom appendKey function (previously only took a path to a single request attribute). Now takes (request, response) objects and returns some value to be appended to the cache key.
295- **v1.0.0** - stamping v0.11.2 into official production version, will now begin developing on branch v2.x (redesign)
296- **v0.11.2** - dev-deps update, courtesy of @danielsogl
297- **v0.11.1** - correction to status code caching, and max-age headers are no longer sent when not cached. middlewareToggle now works as intended with example of statusCode checking (checks during shouldCacheResponse cycle)
298- **v0.11.0** - Added string support to defaultDuration option, previously just numeric ms - thanks @davebaol
299- **v0.10.0** - added ability to blacklist headers (prevents caching) via options.headersBlacklist (thanks @andredigenova)
300- **v0.9.1** - added eslint in prep for v1.x branch, minor ES6 to ES5 in master branch tests
301- **v0.9.0** - corrected Node v7.7 & v8 conflicts with restify (huge thanks to @svozza
302 for chasing this down and fixing upstream in restify itself). Added coveralls. Added
303 middleware.localOptions support (thanks @vectart). Added ability to overwrite/embed headers
304 (e.g. "cache-control": "no-cache") through options.
305- **v0.8.8** - corrected to use node v7+ headers (thanks @peteboere)
306- **v0.8.6, v0.8.7** - README update
307- **v0.8.5** - dev dependencies update (thanks @danielsogl)
308- **v0.8.4** - corrected buffer accumulation, with test support (thanks @ubergesundheit)
309- **v0.8.3** - added tests for x-apicache-bypass and x-apicache-force-fetch (legacy) and fixed a bug in the latter (thanks @Red-Lv)
310- **v0.8.2** - test suite and mock API refactor (thanks @svozza)
311- **v0.8.1** - fixed restify support and added appropriate tests (thanks @svozza)
312- **v0.8.0** - modifies response accumulation (thanks @killdash9) to support res.write + res.end accumulation, allowing integration with restify. Adds gzip support (Node v4.3.2+ now required) and tests.
313- **v0.7.0** - internally sets cache-control/max-age headers of response object
314- **v0.6.0** - removed final dependency (debug) and updated README
315- **v0.5.0** - updated internals to use res.end instead of res.send/res.json/res.jsonp, allowing for any response type, adds redis tests
316- **v0.4.0** - dropped lodash and memory-cache external dependencies, and bumped node version requirements to 4.0.0+ to allow Object.assign native support
317
\No newline at end of file