koa-cash
HTTP response caching for Koa. Supports Redis, in-memory store, and more!
Table of Contents
Features
Caches the response based on any arbitrary store you'd like.
- Handles JSON and stream bodies
- Handles gzip compression negotiation (if
options.compression
is set totrue
as of v4.0.0) - Handles 304 responses
🎉 Pairs great with @ladjs/koa-cache-responses 🎉
Install
npm:
npm install koa-cash
yarn:
yarn add koa-cash
Usage
const koaCash = ; // ... app app;
API
app.use(koaCash(options))
Options are:
maxAge
Default max age (in milliseconds) for the cache if not set via await ctx.cashed(maxAge)
.
threshold
Minimum byte size to compress response bodies. Default 1kb
.
compression
If a truthy value is passed, then compression will be enabled. This value is false
by default.
setCachedHeader
If a truthy value is passed, then X-Cached-Response
header will be set as HIT
when response is served from the cache. This value is false
by default.
hash()
A hashing function. By default, it's:
{ return ctxresponseurl; // same as ctx.url}
ctx
is the Koa context and is also passed as an argument. By default, it caches based on the URL.
get()
Get a value from a store. Must return a Promise, which returns the cache's value, if any.
{ return Promise;}
Note that all the maxAge
stuff must be handled by you. This module makes no opinion about it.
set()
Set a value to a store. Must return a Promise.
{ return Promise;}
Note: maxAge
is set by .cash = { maxAge }
. If it's not set, then maxAge
will be 0
, which you should then ignore.
Example
Using a library like lru-cache, though this would not quite work since it doesn't allow per-key expiration times.
const koaCash = ;const LRU = ; const cache = maxAge: 30000 // global max age app
See @ladjs/koa-cache-responses test folder more examples (e.g. Redis with ioredis
).
const cached = await ctx.cashed([maxAge])
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.body=
and this will cache the response.
Notes
- Only
GET
andHEAD
requests are cached. - Only
200
responses are cached. Don't set304
status codes on these routes - this middleware will handle it for you - The underlying store should be able to handle
Date
objects as well asBuffer
objects. Otherwise, you may have to serialize/deserialize yourself.
Usage
Contributors
Name | Website |
---|---|
Jonathan Ong | http://jongleberry.com |
Nick Baugh | http://niftylettuce.com |