diff --git a/middleware/lru-cache.js b/middleware/lru-cache.js index 4be27b186..838cc45b9 100644 --- a/middleware/lru-cache.js +++ b/middleware/lru-cache.js @@ -36,6 +36,27 @@ module.exports = function(options = {}) { memoryCache.set(key, value, maxAge * 1000); } }, + + /** + * + * 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; + }, }; return async function cache(ctx, next) { diff --git a/middleware/redis-cache.js b/middleware/redis-cache.js index 0115fe9fa..6ec659ee9 100644 --- a/middleware/redis-cache.js +++ b/middleware/redis-cache.js @@ -57,6 +57,27 @@ module.exports = function(options = {}) { await redisClient.setex(key, maxAge, value); } }, + + /** + * + * 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; + }, }; return async function cache(ctx, next) { diff --git a/routes/typora/changelog.js b/routes/typora/changelog.js index b848f6b1f..e0309d18d 100644 --- a/routes/typora/changelog.js +++ b/routes/typora/changelog.js @@ -14,13 +14,7 @@ module.exports = async (ctx) => { const $ = cheerio.load(response.data); - const parseContent = async (link) => { - // Check cache - const cache = await ctx.cache.get(link); - if (cache) { - return Promise.resolve(JSON.parse(cache)); - } - + const loadContent = async (link) => { const response = await axios({ method: 'get', url: link, @@ -36,17 +30,13 @@ module.exports = async (ctx) => { // const author = $('.post-meta span').text(); const html = $('#pagecontainer').html(); - const result = { + return { title: title, link: link, guid: link, pubDate: pubDate, description: html, }; - - ctx.cache.set(link, JSON.stringify(result), 3 * 60 * 60); - - return result; }; const items = await Promise.all( @@ -55,7 +45,7 @@ module.exports = async (ctx) => { .map(async (item) => { const node = $('a', item); const link = node.attr('href'); - const result = await parseContent(link); + const result = await ctx.cache.tryGet(link, async () => loadContent(link), 3 * 60 * 60); return Promise.resolve(result); })