/
cache.js
74 lines (73 loc) · 1.71 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* This is a wrapper store that can add caching to a store
*/
var when = require("promised-io/promise").when;
exports.Cache = function(store, cacheStore, options){
options = options || {};
var defaultExpiresTime = options.defaultExpiresTime || 2000;
var cacheWrites = "cacheWrites" in options ? options.cacheWrites : true;
var cleanupInterval = options.cleanupInterval || 1000;
var lastAccess = {};
var nextCheck = new Date().getTime();
var now;
cleanup();
function cleanup(){
now = new Date().getTime();
if(now > nextCheck){
nextCheck = now + cleanupInterval;
return when(cacheStore.query("expires<$1", {parameters:[now]}), function(results){
results.forEach(function(object){
cacheStore["delete"](object.id);
});
});
}
}
return {
get: function(id){
var cached = cacheStore.get(id);
lastAccess[id] = now++;
if(!cached){
if(store){
cacheStore.put(cached = store.get(id), {id:id});
}
}
return cached;
},
put: function(object, id){
cleanup();
if(!object.expires){
object.autoExpires = true;
object.expires = new Date().getTime() + defaultExpiresTime;
}
if(cacheWrites){
cacheStore.put(object, id);
}
if(store){
return store.put(object, id);
}
},
add: function(object, id){
cleanup();
if(!object.expires){
object.autoExpires = true;
object.expires = new Date().getTime() + defaultExpiresTime;
}
if(cacheWrites){
cacheStore.add(object, id);
}
if(store){
return store.add(object, id);
}
},
query: function(query, options){
return store.query(query, options);
},
"delete": function(id){
cleanup();
if(store){
store["delete"](id);
}
cacheStore["delete"](id);
}
};
};