diff --git a/backend/src/middleware/cache.js b/backend/src/middleware/cache.js new file mode 100644 index 0000000..ec89bd7 --- /dev/null +++ b/backend/src/middleware/cache.js @@ -0,0 +1,28 @@ +// 简单缓存中间件 +const cache = new Map(); + +const cacheMiddleware = (req, res, next) => { + if (req.method !== 'GET') { + return next(); + } + + const key = req.originalUrl; + + if (cache.has(key)) { + const { data, expiry } = cache.get(key); + if (Date.now() < expiry) { + return res.json(data); + } + cache.delete(key); + } + + const originalJson = res.json.bind(res); + res.json = (data) => { + cache.set(key, { data, expiry: Date.now() + 60000 }); // 1分钟缓存 + return originalJson(data); + }; + + next(); +}; + +module.exports = cacheMiddleware;