-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrouteCache.js
More file actions
28 lines (26 loc) · 915 Bytes
/
Copy pathrouteCache.js
File metadata and controls
28 lines (26 loc) · 915 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 100});
module.exports = duration => (req,res,next) => {
//if req is not GET
if(req.method !== 'GET') {
console.error('Cannot cache non-GET methods!');
return next();
}
//check if key exists in cache
const key = req.originalUrl;
const cacheResponse = cache.get(key);
//if exists, send cache result
if(cacheResponse) {
console.log('Cache hit for '.brightGreen.bold + `${key}`.green.italic);
res.send(cacheResponse);
} else {
//if not, replace ,send with method to set response to cache
console.log('Cache miss for '.brightMagenta.bold + `${key}`.magenta.italic);
res.originalSend = res.send;
res.send = body => {
res.originalSend(body);
cache.set(key, body, duration);
};
return next();
}
}