Created
February 3, 2013 15:10
-
-
Save numero-trey/4702128 to your computer and use it in GitHub Desktop.
Quick and easy expiring cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cacheData = {}, | |
ttl = 60000; // default TTL is 60 seconds | |
// Set the TTL | |
exports.setTTL = function(val) { ttl = val; }; | |
// Set cache value | |
exports.set = function(key, value) { | |
cacheData[key] = { | |
val: value, | |
expires: new Date().getTime() + ttl | |
}; | |
}; | |
// Get value of cache key. | |
// Pass 'hit' and 'miss' callbacks in handlers object | |
exports.get = function(key, handlers) { | |
var data = cacheData[key]; | |
if (data) { | |
if (data.expires < new Date().getTime()) { | |
// Expired data | |
delete cacheData[key]; | |
if (handlers.miss) { handlers.miss(key); }; | |
} else { | |
if (handlers.hit) { handlers.hit(data.val); }; | |
return data.val; | |
} | |
} else { | |
if (handlers.miss) { handlers.miss(key); }; | |
}; | |
} | |
////////////////////////////////////////////////////// | |
// Example | |
// var quickCache = require('quick_cache'); | |
// | |
// quickCache.get('cache_key', { | |
// hit: function (val) { | |
// doSomething(val); | |
// }, | |
// miss: function(key) { | |
// dbLookup('blah blah blah', function(val) { | |
// quickCache.set(key, val); | |
// doSomething(val); | |
// }); | |
// }; | |
// }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment