-
Notifications
You must be signed in to change notification settings - Fork 1
/
wrap.js
34 lines (34 loc) · 964 Bytes
/
wrap.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
// A General wrapper with cache and batch and timeouts
module.exports = function Wrap(fn) {
var requestBatches = {};
var requestCache = {};
wrapped.cacheLifetime = 1000;
function wrapped(key, callback) {
if (requestCache.hasOwnProperty(key)) {
var value = requestCache[key];
process.nextTick(function () {
callback(null, value);
});
return;
}
if (requestBatches.hasOwnProperty(key)) {
requestBatches[key].push(callback);
return;
}
var batch = requestBatches[key] = [callback];
fn(key, onDone);
function onDone(err, result) {
if (!err && wrapped.cacheLifetime) {
requestCache[key] = result;
setTimeout(function () {
delete requestCache[key];
}, wrapped.cacheLifetime);
}
delete requestBatches[key];
for (var i = 0, l = batch.length; i < l; i++) {
batch[i].apply(null, arguments);
}
}
}
return wrapped;
};