1.0.2 • Published 5 years ago

koa-api-cache v1.0.2

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

koa-api-cache

Supports redis cache koa router response data and auto-clearing.
Only suport request method is GET.

Quick Start

Install

$ npm install koa-api-cache

Redis Client

koa-api-cache can use ioredis redis library to keep its client connections.

Configuration

  • redis: redis client.
  • prefix: redis key prefix - default 'default'
  • expire: redis expire time - unit:second, default '300'
  • conditionFunc: set condition to cache the response content.

Usage

If your api interface response this body.

ctx.body = {
  code: 0,
  msg: "SUCCESS",
  data: {}
}

Add cache to the koa router.

const Redis = require("ioredis");
const redis = new Redis({host: "127.0.0.1", port: "6379", db: 10});
const ApiCache = require("koa-api-cache");
const apiCache = new ApiCache({redis, conditionFunc(body) {
  return body.code === 0
}});
const router = require("koa-router")();
router.get("/api/test",apiCache.route({
  prefix: "test",
  expire: 300,
  conditionFunc (body) {
    return body.code === 0;
  }
}), async ctx => {})

If you want to clear cache.

await apiCache.delCache("test");

API Docs

ApiCache.prototype.route({prefix, expire, conditionFunc}) => Promise

  • prefix string, redis cache prefix
  • expire number, redis ttl
  • conditionFunc function, set condition to cache the response content

ApiCache.prototype.delCache(prefix) => Promise

  • prefix string, redis cache prefix
1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago