-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacheMiddleware.js
More file actions
32 lines (31 loc) · 843 Bytes
/
cacheMiddleware.js
File metadata and controls
32 lines (31 loc) · 843 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
29
30
31
32
const debug = require('debug')('app:cacheMiddleware')
const flatCache = require('flat-cache')
let cache = flatCache.load('cacheId')
function del(key) {
cache.removeKey(key)
}
module.exports = function cacheMiddleware(req, res, next) {
(async function pos() {
try {
let key = '__express__' + req.originalUrl || req.url
let cacheContent = cache.getKey(key)
if (cacheContent) {
debug('loading from cache')
res.send(cacheContent)
return
} else {
res.sendResponse = res.send
res.send = (body) => {
cache.setKey(key, body)
cache.save()
setTimeout(del, 3000, key)
//setTimeout(cache.removeKey(key), 60000);
res.sendResponse(body)
}
next()
}
} catch (err) {
debug(err.stack)
}
}());
}