HTTP response caching for Koa. Modified from official koa-cash, allowing excluding and whitelisted paths.
Caches the response based on any arbitrary store you'd like.
- Handles JSON and stream bodies
- Handles gzip compression negotiation
- Handles 304 responses
- Handles whitelisted and blacklisted paths.
app.use(require('koa-cash')({
// some options
}))
app.use(async (ctx, next) => {
// this response is already cashed if `true` is returned,
// so this middleware will automatically serve this response from cache
if (await ctx.cashed()) return
// set the response body here,
// and the upstream middleware will automatically cache it
ctx.response.body = 'hello world!'
})Options are:
Default max age (in milliseconds) for the cache if not set via await ctx.cashed(maxAge).
Minimum byte size to compress response bodies. Default 1kb.
A hashing function. By default, it's:
function hash(ctx) {
return ctx.request.url
}ctx is the Koa context. By default, it caches based on the URL.
Get a value from a store. Can be a regular function or an async function,
which returns the cache's value, if any.
async function get(key, maxAge) {
return <cached-value>
}Note that all the maxAge stuff must be handled by you.
This module makes no opinion about it.
Set a value to a store. Can be a regular function or an async function.
async function set(key, value, maxAge) {
...
}Set a list of whitelisted paths, in which caching will be turned on.
app.use(require('koacash')){
get: async (key, maxAge) => {
// Your own get() implementation
},
set: async (key, value, maxAge) => {
// Your own set() implementation
},
allowed: [
'/foo', '/bar'
]
}Similar to options.allowed, but when both params are supplied, but for any routes that are both in excluded list and allowed list, excluded list prevails.
Note: maxAge is set by .cash={ maxAge }.
If it's not set, then maxAge will be 0, which you should then ignore.
Using a library like lru-cache, though this would not quite work since it doesn't allow per-key expiration times.
var cache = require('lru-cache')({
maxAge: 30000 // global max age
})
app.use(require('koa-cash')({
get (key, maxAge) {
return cache.get(key)
},
set (key, value) {
cache.set(key, value)
}
}))This is how you enable a route to be cached.
If you don't call await ctx.cashed(),
then this route will not be cached nor will it attempt to serve the request from the cache.
maxAge is the max age passed to get().
If cached is true,
then the current request has been served from cache and you should early return.
Otherwise, continue setting ctx.response.body= and this will cache the response.
- Only
GETandHEADrequests are cached. - Only
200responses are cached. Don't set304status codes on these routes - this middleware will handle it for you - The underlying store should be able to handle
Dateobjects as well asBufferobjects. Otherwise, you may have to serialize/deserialize yourself.