koa-cache

0.1.0 • Public • Published

koa-cache

Redis Content Cache with polcies

Build Status

WORKING IN PROGRESS

Notes about Redis

LRU

Making the cache more efficient in a limited space requires certain eviction algorithm that delete entries after the memory is drained.

By default redis emploies a policy named volatile-lru, which only evicts keys that have been set with an expire.

You should note that a cache entry may be deleted from Redis regardless of control of this middleware if the redis is configured to use some different evition policy.

Expiration

On the other side, EXPIRE command will not always ensure a key is deleted due to the probabilistic algorithm used by Redis. And this behavior cannot be alterd or configured.

Key-Value

For performance concern, we only use the simple key-value storage of Redis, instead of the various data structures like hash, set.

By defualt, all the keys of cache entries are prefixed by koa-cache.

Usage

Sample can be found at tests/app.js

Context helper

ctx is a koa context.

ctx.cache([key,value])

Set or get a cache. If no arguments given, will read cache using ctx.cacheKey() to retrive default key.

ctx.cacheKey([key])

Set or get a cache key in session.

If key is given, it will save this.req.url and key pair in session.

Otherwise, it retrieve cache key from session using this.req.url.

ctx.invalidate([key])

Delete a cache entry by key. If key is not given, will delete using key generated by ctx.cacheKey().

Cache middlewares

To get a cache instance

var cache = require("koa-cache")();

cache.all()

Cache all result for this url:

app.get("/data", cache.all(), function*() {
  this.body = "hello";
});

Session aware:

app.get("/data", cache.all(), function*() { // using user name as cache key this.cacheKey(this.session.username);

//deliver content of session-related this.body = this.session.username; });

cache.match(matcherGenFunc)

  • Using matcherGenFunc to determin if we are reading from cache.
  • Useful if we are dealing with user context, e.g, reading cache for a specific user
app.get("/data", cache.match(function*() {
  if(this.session.user) {
    return true;
  }
  return false;
}), function*() {
  this.body = "private!";
  
  // can be used with cacheKey
  this.cacheKey(this.session.user.name);
});

License

See ./LICENSE

Readme

Keywords

Package Sidebar

Install

npm i koa-cache

Weekly Downloads

7

Version

0.1.0

License

MIT

Last publish

Collaborators

  • robinqu