diff --git a/lib/middleware/cache/index.js b/lib/middleware/cache/index.js index 05bf29a2e8..52c0b3aeaa 100644 --- a/lib/middleware/cache/index.js +++ b/lib/middleware/cache/index.js @@ -56,6 +56,9 @@ module.exports = function (app) { app.context.cache = { ...cacheModule, tryGet: async (key, getValueFunc, maxAge = config.cache.contentExpire, refresh = true) => { + if (typeof key !== 'string') { + throw Error('Cache key must be a string'); + } let v = await get(key, refresh); if (!v) { v = await getValueFunc(); diff --git a/lib/v2/test/index.js b/lib/v2/test/index.js index 38ebf88ca9..91741841fa 100644 --- a/lib/v2/test/index.js +++ b/lib/v2/test/index.js @@ -75,6 +75,21 @@ module.exports = async (ctx) => { link: `https://github.com/DIYgod/RSSHub/issues/0`, author: `DIYgod0`, }); + } else if (ctx.params.id === 'cacheUrlKey') { + const description = await ctx.cache.tryGet( + new URL('https://rsshub.app'), + () => ({ + text: `Cache${++cacheIndex}`, + }), + config.cache.routeExpire * 2 + ); + item.push({ + title: 'Cache Title', + description: description.text, + pubDate: new Date(`2019-3-1`).toUTCString(), + link: `https://github.com/DIYgod/RSSHub/issues/0`, + author: `DIYgod0`, + }); } else if (ctx.params.id === 'complicated') { item.push({ title: `Complicated Title`, diff --git a/test/middleware/cache.js b/test/middleware/cache.js index bae584f079..88a138ba66 100644 --- a/test/middleware/cache.js +++ b/test/middleware/cache.js @@ -190,4 +190,17 @@ describe('cache', () => { expect(parsed1.items[0].content).toBe('Cache1'); expect(parsed2.items[0].content).toBe('Cache2'); }); + + it('throws URL key', async () => { + process.env.CACHE_TYPE = 'memory'; + server = require('../../lib/index'); + const request = supertest(server); + + try { + const response = await request.get('/test/cacheUrlKey'); + expect(response).toThrow(Error); + } catch (e) { + expect(e.message).toContain('Cache key must be a string'); + } + }); });