Koa-incache requires koa2 and node v7.6.0 or higher
npm install koa-incache --save
const cache = require('koa-incache');
const koa = require('koa');
const app = new koa();
app.use(cache());
app.use(ctx=>{
const result = 'hello world';
ctx.cached(result);
ctx.body = result;
});
app.listen(3000);
The cache is made using ctx.originalUrl
as key
const fs = require('fs');
const cache = require('koa-incache');
const koa = require('koa');
const Router = require('koa-router');
const app = new koa();
const router = new Router();
app.use(cache({
maxAge: 60000 // 1 minute max age
}));
router.get('/this/is/cached', function (ctx, next) {
const content = fs.readFileSync('myFile');
ctx.cached(content);
ctx.body = content;
});
router.get('/this/is/not/cached', function (ctx, next) {
const content = fs.readFileSync('myFile');
ctx.body = content;
});
router.get('/uncache', function (ctx, next) {
const content = fs.readFileSync('myFile');
ctx.cached(content);
if(foo)
ctx.uncache();
ctx.body = content;
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
From koa context it's possible get InCache by ctx.cache
router.get('/my/root', function (ctx, next) {
ctx.cache.set('my key', 'my value');
//...
});
cached
accept an argument that is the content to be storeduncache
remove cache for context rootFor more info about InCache click here
You can view the changelog here
koa-incache is open-sourced software licensed under the MIT license
Fabio Ricali
Davide Polano