-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
49 lines (44 loc) · 1.39 KB
/
cache.js
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const l = require('./log.js').log;
module.exports = function Cache(config) {
const memcache = config.memcache;
const expireTime = config.expireTime || 86400;
return {
// Returns a promise for the value from cache (null on a miss)
getCachedResponse: function(req) {
return new Promise(function(resolve, reject) {
req.cacheKey = getCacheKey(req);
memcache.get(req.cacheKey, (err, data) => {
req.fromCache = !!(!err && data);
if (err) {
l("Cache error: " + err);
}
resolve(data || null);
});
})
},
// Stores the value in the cache and returns a promise to the same value
setCachedResponse: function(req, css) {
return new Promise(function(resolve, reject) {
if (req.fromCache) {
return resolve(css);
}
memcache.set(req.cacheKey, css, expireTime, (err, data) => {
resolve(css);
});
})
}
}
}
function getCacheKey(req) {
return md5([
req.session && req.session.token,
req.body,
JSON.stringify(req.parserOptions) || ''
]);
}
function md5(strings) {
var crypto = require('crypto');
var hasher = crypto.createHash('md5');
strings.forEach(string => hasher.update(String(string)));
return hasher.digest('hex');
}