From c893d1ad17344ec8bd7e4e2307ea593128cf3948 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Fri, 18 May 2018 01:31:51 +0800 Subject: [PATCH] app: expose cache function to koa context --- middleware/lru-cache.js | 5 +++++ middleware/redis-cache.js | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/middleware/lru-cache.js b/middleware/lru-cache.js index ead097f78..f607a287d 100644 --- a/middleware/lru-cache.js +++ b/middleware/lru-cache.js @@ -21,6 +21,11 @@ module.exports = function(options = {}) { max: maxLength, }); + options.app.context.cache = { + get: (key) => memoryCache.get(key), + set: (key, value, maxAge) => memoryCache.set(key, value, maxAge), + }; + return async function cache(ctx, next) { const { url, path } = ctx.request; const resolvedPrefix = typeof prefix === 'function' ? prefix.call(ctx, ctx) : prefix; diff --git a/middleware/redis-cache.js b/middleware/redis-cache.js index 72c7ad11c..92ce06081 100644 --- a/middleware/redis-cache.js +++ b/middleware/redis-cache.js @@ -39,6 +39,11 @@ module.exports = function(options = {}) { onconnect(); }); + options.app.context.cache = { + get: async (key) => await redisClient.get(key), + set: async (key, value, maxAge) => await redisClient.setex(key, maxAge, value), + }; + return async function cache(ctx, next) { const { url, path } = ctx.request; const resolvedPrefix = typeof prefix === 'function' ? prefix.call(ctx, ctx) : prefix;