Coder Social home page Coder Social logo

koa-router-cache's Introduction

koa-router-cache

Router cache middleware for koa@1.

Install

npm i koa-router-cache --save

Usage

cache(app, options)

Options:

  • key: {String|GeneratorFunction} cache key. (Required)
  • expire: {Number} expire time, in ms. (Required)
  • get: {GeneratorFunction} custom getter function for getting data from cache. (Required)
  • set: {GeneratorFunction} custom setter function for setting data to cache. (Required)
  • passthrough: {GeneratorFunction} whether pass request through, return an object. (Required)
    • shouldCache: {Boolean} whether cache this result
    • shouldPass: {Boolean} whether pass this request through
  • evtName: {String} event name for destroy cache. (Optional)
  • destroy: {function} destroy cache. (Optional)
  • pathToRegexp {Object} pathToRegexp options, see https://github.com/pillarjs/path-to-regexp#usage. (Optional)

Example

koa-router-cache build-in simple MemoryCache and RedisCache, also you can write by yourself.

MemoryCache

'use strict';
 
var app = require('koa')();
var cache = require('koa-router-cache');
var MemoryCache = cache.MemoryCache;
 
var count = 0;
 
app.use(cache(app, {
  'GET /': {
    key: 'cache:index',
    expire: 2 * 1000,
    get: MemoryCache.get,
    set: MemoryCache.set,
    passthrough: MemoryCache.passthrough,
    evtName: 'clearIndexCache',
    destroy: MemoryCache.destroy
  }
}));
 
app.use(function* () {
  if (this.path === '/') {
    this.body = count++;
    if (count === 3) {
      count = 0;
      this.app.emit('clearIndexCache');
    }  
  }
});
 
app.listen(3000, function () {
  console.log('listening on 3000.');
});

RedisCache

'use strict';

var app = require('koa')();
var cache = require('koa-router-cache');
var RedisCache = cache.RedisCache();// or RedisCache(client)

var count = 0;

app.use(cache(app, {
  'GET /': {
    key: 'cache:index',
    expire: 2 * 1000,
    get: RedisCache.get,
    set: RedisCache.set,
    passthrough: RedisCache.passthrough,
    evtName: 'clearIndexCache',
    destroy: RedisCache.destroy
  }
}));

app.use(function* () {
  if (this.path === '/') {
    this.body = {
      count: count++
    };
    if (count === 3) {
      count = 0;
      this.app.emit('clearIndexCache');
    }
  }
});

app.listen(3000, function () {
  console.log('listening on 3000.');
});

another usage:

// Guests share one index page cache
GET /': {
  key: 'cache:index',
  expire: 10 * 1000,
  get: MemoryCache.get,
  set: MemoryCache.set,
  destroy: MemoryCache.destroy,
  passthrough: function* passthrough(_cache) {
    // Guests
    if (!this.session || !this.session.user) {
      if (_cache == null) {
        return {
          shouldCache: true,
          shouldPass: true
        };
      }
      this.type = 'text/html; charset=utf-8';
      this.set('content-encoding', 'gzip');
      this.body = _cache;
      return {
        shouldCache: true,
        shouldPass: false
      };
    }
    // Logged-in users
    return {
      shouldCache: false,
      shouldPass: true
    };
  }
}

Test

npm test

License

MIT

koa-router-cache's People

Contributors

nswbmw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

henryxie2093

koa-router-cache's Issues

POST url不支持吗

'POST /abc': {
passthrough: function* passthrough(_cache) {
console.log(_cache)
}
}

这样进不到console

关于执行流程的以后

'use strict';

var koa = require('koa');
var cache = require('koa-router-cache');
var MemoryCache = cache.MemoryCache;
var app = koa();
var count = 0;

app.use(cache(app, {
  'GET /' :{
    key: 'cache:index',
    expire: 5 * 1000 ,
    get: MemoryCache.get,
    set: MemoryCache.set,
    passthrough: MemoryCache.passthrough,
    evtName: 'clearIndexCache',
    destroy: MemoryCache.destroy 
  }
}));

app.use(function *() {
  var d = new Date();
  var strDate = (d.getMinutes()+1)+':'+ (d.getSeconds()+1);
  this.body = count++;
  console.log(strDate +' - '+ this.body);  // 这块每次通过浏览器请求的时候都会执行
  if(count === 5){
    count = 0;
    this.app.emit('clearIndexCache');
  }
});

app.listen(3000, function () {
  console.log('listening on 3000');
});

console.log(strDate +' - '+ this.body); // 这块每次通过浏览器请求的时候都会执行
并且每次输出的值也不一样

51:10 - 0
51:11 - 1
51:14 - 2
51:18 - 3
51:18 - 4
51:21 - 0
51:22 - 1
51:26 - 2
51:29 - 3
51:29 - 4

但是浏览器重展示的 数据5s 以内是一样的,有点糊涂了,求解惑

是我理解错了:使用 koa 搭建论坛系统 中的描述!

以上代码的意思是:缓存主页并 5 秒更新一次,第一次请求到来时缓存中间件中没有内容,所以传递到下一个中间件,此时将 this.body 赋值为 0 , count 变为 1,当中间件的 downstream 执行完毕后执行 upstream,此时将 this.body = 0 缓存到内存中,并设置 5 秒的生存期,所以,后续 5 秒之内的所有请求都会因命中缓存而返回 0 。5 秒过后,因为缓存中的内容已经过期被删除,所以下个请求到来时没有命中缓存,此时传递到下一个中间件将 this.body 赋值为 1 , count 变为 2,并更新缓存。直到当 count 变为 5 时,count 被重置为 0,并通过事件触发该路径对应的监听器立即删除缓存中的老数据,这样保证了缓存中的数据都是最新的。

我理解的是:每5s 刷新后,count 递增+1 依次出现,5s 没刷新这个数不会变。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.