forked from ERNICommunity/at11
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.js
31 lines (26 loc) · 771 Bytes
/
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
var config = require('./config');
module.exports = new (function() { // jshint ignore:line
var cache = {};
setInterval(cleanUp, config.cacheExpiration);
this.set = function(key, value) {
if(typeof value !== "object")
{
throw "Only objects can be cached";
}
cache[key] = { value: value, timestamp: Date.now() };
};
this.get = function(key) {
return isValid(key) ? cache[key] : null;
};
function isValid(key) {
var enterTime = cache[key] && cache[key].timestamp;
return !!enterTime && (enterTime + config.cacheExpiration > Date.now());
}
function cleanUp() {
for(var key in cache){
if(cache.hasOwnProperty(key) && !isValid(key)){
delete cache[key];
}
}
}
})();