Created
January 15, 2014 21:53
-
-
Save freshlogic/8445490 to your computer and use it in GitHub Desktop.
Returns data from cache if available; otherwise executes the specified function and places the results in cache before returning the data.
This file contains hidden or 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 redis = require('redis'); | |
| function Cache(port, host, options) { | |
| this.client = redis.createClient(port, host, options); | |
| }; | |
| // Returns data from cache if available; | |
| // otherwise executes the specified function and places the results in cache before returning the data. | |
| Cache.prototype.fetch = function(key, func, options, callback) { | |
| // Options are optional | |
| if(!callback) { | |
| callback = options; | |
| } | |
| this.client.get(key, function(err, data) { | |
| if(err) { | |
| return callback(err); | |
| } | |
| if(data) { | |
| return callback(null, JSON.parse(data)); | |
| } | |
| var client = this.client; | |
| func(function(err, data) { | |
| if(err) { | |
| return callback(err); | |
| } | |
| // Default expire time is 30 to 60 seconds | |
| var expire = (options && options.expire) ? options.expire : Math.floor(Math.random() * (60000 - 30000 + 1) + 30000); | |
| client.psetex(key, expire, JSON.stringify(data)); | |
| return callback(null, data); | |
| }); | |
| }); | |
| }; | |
| exports.createClient = function(port, host, options) { | |
| return new Cache(port, host, options); | |
| }; | |
| // Usage | |
| var cache = require('./cache').createClient(6379, 'localhost'); | |
| var request = require('request'); | |
| cache.fetch('what-is-my-ip', function(callback) { | |
| request.get('http://ip.jsontest.com', { json: true }, callback); | |
| }, function(err, ip) { | |
| console.log(ip); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment