• Stars
    star
    154
  • Rank 233,619 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

HTTP response caching for Koa. Supports Redis, in-memory store, and more!

koa-cash

build status code coverage code style styled with prettier made with lass license npm downloads

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 to true 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

import LRU from 'lru-cache';
import koaCash from 'koa-cash';

// ...
const cache = new LRU();
app.use(koaCash({
  get: (key) => {
    return cache.get(key);
  },
  set(key, value) {
    return cache.set(key, value);
  },
}))

app.use(async ctx => {
  // 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.body = 'hello world!';
});

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.

methods

If an object is passed, then add extra HTTP method caching. This value is empty by default. But GET and HEAD are enabled.

Eg: { POST: true }

hash()

A hashing function. By default, it's:

function hash(ctx) {
 return ctx.response.url; // 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.

function get(key, maxAge) {
  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.

function set(key, value, maxAge) {
  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 = require('koa-cash');
const LRU = require('lru-cache');

const cache = new LRU({
  maxAge: 30000 // global max age
})

app.use(koaCash({
  get (key, maxAge) {
    return cache.get(key)
  },
  set (key, value) {
    cache.set(key, value)
  }
}))

See @ladjs/koa-cache-responses test folder more examples (e.g. Redis with ioredis).

Max age (optional)

const cached = await ctx.cashed(maxAge) // maxAge is passed to your caching strategy

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.

CashClear

ctx.cashClear('/')

This is a special method available on the ctx that you can use to clear the cache for a specific key.

Notes

  • Only GET and HEAD requests are cached. (Unless overridden)
  • Only 200 responses are cached. Don't set 304 status codes on these routes - this middleware will handle it for you
  • The underlying store should be able to handle Date objects as well as Buffer objects. Otherwise, you may have to serialize/deserialize yourself.

Contributors

Name Website
Jonathan Ong http://jongleberry.com
Nick Baugh http://niftylettuce.com

License

MIT © Jonathan Ong

Links

More Repositories

1

koa

Expressive middleware for node.js using ES2017 async functions
JavaScript
34,326
star
2

examples

Example Koa apps
JavaScript
4,471
star
3

jwt

Koa middleware for validating JSON Web Tokens
JavaScript
1,333
star
4

bodyparser

Koa body parsing middleware
TypeScript
1,273
star
5

static

Static file server middleware
JavaScript
1,124
star
6

compose

Middleware composition utility
JavaScript
986
star
7

koa-body

koa body parser middleware
TypeScript
923
star
8

session

Simple session middleware for koa
JavaScript
895
star
9

router

Router middleware for Koa. Maintained by @forwardemail and @ladjs.
JavaScript
790
star
10

cors

Cross-Origin Resource Sharing(CORS) for koa
JavaScript
723
star
11

kick-off-koa

[MAINTAINERS WANTED] An intro to koa via a set of self-guided workshops
JavaScript
693
star
12

logger

Development style logging middleware
JavaScript
561
star
13

mount

Mount other Koa applications or middleware to a given pathname
JavaScript
549
star
14

ratelimit

Rate limiter middleware
JavaScript
466
star
15

joi-router

Configurable, input and output validated routing for koa
JavaScript
451
star
16

route

Simple route middleware
JavaScript
442
star
17

workshop

Koa Training Workshop
JavaScript
436
star
18

compress

Compress middleware for koa
JavaScript
432
star
19

koa.io

[MAINTAINERS WANTED] Realtime web framework combine koa and socket.io.
JavaScript
427
star
20

send

Transfer static files
TypeScript
420
star
21

generic-session

koa session store with memory, redis or others.
JavaScript
414
star
22

koa-redis

Redis storage for Koa session middleware/cache with Sentinel and Cluster support
JavaScript
353
star
23

koala

[SEEKING MAINTAINER] An HTTP/2 and ES6 Module-ready Koa Suite
JavaScript
318
star
24

static-cache

[MAINTAINERS WANTED] Static cache for koa
JavaScript
293
star
25

csrf

CSRF tokens for koa
JavaScript
265
star
26

react-view

A Koa view engine which renders React components on server
JavaScript
256
star
27

convert

Convert koa generator-based middleware to promise-based middleware
JavaScript
253
star
28

ejs

a koa view render middleware, support all feature of ejs
JavaScript
245
star
29

json

pretty-printed JSON response middleware
JavaScript
197
star
30

todo

a todo example write with koa and react
JavaScript
165
star
31

koa-hbs

Handlebars templates for Koa.js
JavaScript
158
star
32

onerror

an error handler for koa, hack ctx.onerror
JavaScript
139
star
33

basic-auth

blanket basic auth middleware
JavaScript
138
star
34

multer

Middleware for handling `multipart/form-data` for koa, based on Express's multer.
JavaScript
137
star
35

userauth

koa user auth middleware
JavaScript
134
star
36

response-time

X-Response-Time middleware
JavaScript
124
star
37

trie-router

Trie-routing for Koa
JavaScript
120
star
38

koa-roles

koa version of Connect-Roles
JavaScript
117
star
39

etag

ETag support for Koa responses
JavaScript
112
star
40

bunyan-logger

Koa middleware for bunyan request logging
JavaScript
108
star
41

favicon

Koa middleware for serving a favicon
JavaScript
104
star
42

error

Error response middleware (text, json, html)
JavaScript
103
star
43

rewrite

URL rewriting middleware
JavaScript
100
star
44

json-filter

Middleware allowing the client to filter the response to only what they need, reducing the amount of traffic over the wire.
JavaScript
92
star
45

json-error

Error handler for pure-JSON apps
JavaScript
89
star
46

qs

qs for koa, and use querystring more safely.
JavaScript
85
star
47

bigpipe-example

[DEPRECATED] BigPipe using koa and component
JavaScript
83
star
48

common

[DEPRECATED] USE INDIVIDUAL MODULES
JavaScript
77
star
49

locales

koa locales, i18n solution for koa
JavaScript
67
star
50

koa-lusca

koa version of lusca. Application security for koa.
JavaScript
65
star
51

cluster

Koa clustering and error handling utility
JavaScript
64
star
52

parameter

parameter validate middleware for koa, powered by parameter
JavaScript
62
star
53

conditional-get

Conditional GET middleware for koa
JavaScript
59
star
54

trace

generic tracing for koa
JavaScript
53
star
55

koa-range

[MAINTAINERS WANTED] range request implementation for koa, see http://tools.ietf.org/html/rfc7233
JavaScript
47
star
56

sendfile

basic file-sending utility for koa
JavaScript
45
star
57

koajs.com

The koajs.com website
HTML
42
star
58

mock

Simple web page mock middleware
JavaScript
40
star
59

body-parsers

collection of koa body parsers
JavaScript
37
star
60

koa-markdown

Auto convert markdown to html for koa. Inspired by connect-markdown
JavaScript
37
star
61

koa-gzip

[Deprecated] please use koa-compress instead
JavaScript
36
star
62

file-server

file serving middleware for koa
JavaScript
36
star
63

bundle

Generic asset pipeline with caching, etags, minification, gzipping and sourcemaps.
JavaScript
36
star
64

resourcer

A simple resource directory mounter for koa.
JavaScript
34
star
65

path-match

koa route middleware
JavaScript
33
star
66

html-minifier

minify HTML responses like some crazy guy
JavaScript
30
star
67

webcam-mjpeg-stream

[DEPRECATED] Stream JPEG snapshots from your Mac
JavaScript
28
star
68

timer

time your middleware
JavaScript
26
star
69

statsd

Statsd middleware
JavaScript
24
star
70

redis-session-sets

Koa Redis sessions with field-referencing cross sets
JavaScript
20
star
71

accesslog

Middleware for common log format access logs
JavaScript
19
star
72

is-json

check if a koa body should be interpreted as JSON
JavaScript
17
star
73

charset

use iconv-lite to encode the body and set charset to content-type
JavaScript
16
star
74

koa-safe-jsonp

Safe jsonp plusins for koa.
JavaScript
16
star
75

trace-influxdb

InfluxDB tracing for koa-trace
JavaScript
15
star
76

stateless-csrf

CSRF without sessions.
JavaScript
15
star
77

atomic-session

DEPRECATED
JavaScript
15
star
78

koa-github

simple github auth middleware for koa
JavaScript
13
star
79

cross-cookies

Easily set cookies across subdomains
JavaScript
13
star
80

s3-cache

Koa middleware to cache and serve from S3
JavaScript
11
star
81

eslint-config-koa

Koa's ESLint config, based on Standard
JavaScript
11
star
82

ctx-cache-control

Augment Koa with ctx.cacheControl(maxAge)
JavaScript
9
star
83

snapshot

take snapshot when request, cache by request path.
JavaScript
9
star
84

compressor

[DEPRECATED] Compress middleware for koa that always compresses
JavaScript
9
star
85

koa-fresh

DEPRECATED
JavaScript
8
star
86

cdn

[DEPRECATED] middleware for a koa-based CDN
JavaScript
7
star
87

koa-rt

koa rt with microtime
JavaScript
6
star
88

override-method

method override utility for koa
JavaScript
6
star
89

ctx-basic-auth

Augments Koa with ctx.basicAuth
JavaScript
5
star
90

resourcer-docs

[MAINTAINERS WANTED] Simple app that generates documentation for routes mounted using koa-resourcer.
JavaScript
5
star
91

middleware-hook

low-level hooks for your middleware
JavaScript
5
star
92

path

[DEPRECATED] path-matching middleware for koa
JavaScript
4
star
93

observable-redis-session

[DEPRECATED] Observable, atomic sessions for Koa using Redis
JavaScript
2
star
94

help

koa(1) executable for instant help
2
star
95

discussions

KoaJS Discussions
1
star