后端: 添加缓存中间件
This commit is contained in:
parent
46afc47477
commit
f411f06b7a
28
backend/src/middleware/cache.js
Normal file
28
backend/src/middleware/cache.js
Normal 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;
|
||||
Loading…
Reference in New Issue
Block a user