Comparing version 0.0.3 to 0.0.4
29
index.js
@@ -38,2 +38,3 @@ /*! | ||
this._cleanupInterval = null; | ||
this._fetching = {}; | ||
@@ -85,13 +86,22 @@ // magical thisness | ||
// events fired: evict, evict:expired, evict:manual, evict:capacity | ||
Goldfish.prototype._fetch = function(populate, key, cb) { | ||
var self = this; | ||
populate(key, function(err, value) { | ||
if (err) return cb(err); | ||
if (this._fetching.hasOwnProperty(key)) { | ||
this._fetching[key].push(cb); | ||
} else { | ||
this._fetching[key] = [cb]; | ||
self._insert(key, value); | ||
cb(null, value); | ||
}); | ||
populate(key, function handlePopulateResponse(err, value) { | ||
var i; | ||
// add to cache if we got a value | ||
if (!err) self._insert(key, value); | ||
// notify everybody waiting on this result (error or value) | ||
for(i=0; i < self._fetching[key].length; ++i) { | ||
self._fetching[key][i](null, value); | ||
} | ||
}); | ||
} | ||
}; | ||
@@ -220,5 +230,2 @@ | ||
exports.createGoldfish = function(options) { | ||
return new Goldfish(options); | ||
}; | ||
exports.EVICT_REASONS = EVICT_REASONS; | ||
module.exports = Goldfish; |
@@ -5,3 +5,3 @@ { | ||
"description": "Evented in-memory cache", | ||
"version": "0.0.3", | ||
"version": "0.0.4", | ||
"repository": { | ||
@@ -8,0 +8,0 @@ "type": "git", |
@@ -1,2 +0,2 @@ | ||
var goldfish = require('../'); | ||
var Goldfish = require('../'); | ||
@@ -12,3 +12,3 @@ describe('#get', function() { | ||
cache = goldfish.createGoldfish({ | ||
cache = new Goldfish({ | ||
populate: function(key, cb) { | ||
@@ -30,2 +30,23 @@ setTimeout(function() { | ||
}); | ||
it('should call populate only once when the same value is being fetched', function(done) { | ||
var cache | ||
, populateCount = 0 | ||
; | ||
cache = new Goldfish({ | ||
populate: function(key, cb) { | ||
++populateCount; | ||
setTimeout(function() { | ||
cb(null, key); | ||
}, 10); | ||
} | ||
}); | ||
cache.get('test', function() {}); | ||
cache.get('test', function(err, value) { | ||
if (populateCount === 1) return done(); | ||
return done(new Error('expected populateCount to be 1')); | ||
}); | ||
}); | ||
}); | ||
@@ -35,3 +56,3 @@ | ||
it('should expire a value after 10ms', function(done) { | ||
var cache = goldfish.createGoldfish({ | ||
var cache = new Goldfish({ | ||
populate: function(key, cb) { | ||
@@ -57,3 +78,3 @@ cb(null, key); | ||
cache = goldfish.createGoldfish({ | ||
cache = new Goldfish({ | ||
populate: function(key, cb) { | ||
@@ -60,0 +81,0 @@ cb(null, key); |
9657
267