后端: 添加缓存中间件

This commit is contained in:
Backend Developer 2026-03-10 10:01:19 +00:00
parent 46afc47477
commit f411f06b7a

View File

@ -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;