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) => {