From e5aa28a79bb6cf7dd07be72bc4576f5c581ec05b Mon Sep 17 00:00:00 2001 From: cnzgray Date: Wed, 14 Nov 2018 12:14:43 +0800 Subject: [PATCH] fix: can not get cache (#1143) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 本补丁主要解决了以下两个问题: 1. 在 a1f060f3d2205fbe5cfc1672ad2bb0212e350c65 提交时,缓存get方法发生了变化。 **cache的get方法未正确返回值**,这将导致所有使用自定义缓存的地方缓存丢失! 2. 同时修正了未设置缓存时系统报`tryGet`方法未定义的问题。 --- index.js | 21 +++++++++++++++++++++ middleware/lru-cache.js | 2 +- middleware/redis-cache.js | 2 +- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 037b20484..5b541e2c4 100644 --- a/index.js +++ b/index.js @@ -95,6 +95,27 @@ if (config.cacheType === 'memory') { app.context.cache = { get: () => null, set: () => null, + + /** + * + * try get from cache. + * if not exists use `getValue` function to get value, and put into cahche. + * + * @param key cache key + * @param getValueFunc a function to get value. call it when key not exists. + * @param maxAge + * + * @returns {Promise} + */ + tryGet: async function(key, getValueFunc, maxAge) { + let v = await this.get(key); + if (!v) { + v = await getValueFunc(); + this.set(key, v, maxAge); + } + + return v; + }, }; } diff --git a/middleware/lru-cache.js b/middleware/lru-cache.js index 838cc45b9..073408f06 100644 --- a/middleware/lru-cache.js +++ b/middleware/lru-cache.js @@ -22,7 +22,7 @@ module.exports = function(options = {}) { options.app.context.cache = { get: (key) => { if (key) { - memoryCache.get(key); + return memoryCache.get(key); } }, set: (key, value, maxAge) => { diff --git a/middleware/redis-cache.js b/middleware/redis-cache.js index 6ec659ee9..309ae776c 100644 --- a/middleware/redis-cache.js +++ b/middleware/redis-cache.js @@ -43,7 +43,7 @@ module.exports = function(options = {}) { options.app.context.cache = { get: async (key) => { if (key) { - await redisClient.get(key); + return await redisClient.get(key); } }, set: async (key, value, maxAge) => {