cache.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var config = require("./config");
  2. var redis = null;
  3. function connect_redis() {
  4. console.log("connecting to redis");
  5. if (process.env.REDISTOGO_URL) {
  6. var rtg = require("url").parse(process.env.REDISTOGO_URL);
  7. redis = require("redis").createClient(rtg.port, rtg.hostname);
  8. redis.auth(rtg.auth.split(":")[1]);
  9. } else {
  10. redis = require("redis").createClient();
  11. }
  12. redis.on("ready", function() {
  13. console.log("Redis connection established.");
  14. });
  15. redis.on("error", function (err) {
  16. console.error(err);
  17. });
  18. redis.on("end", function () {
  19. console.warn("Redis connection lost!");
  20. });
  21. }
  22. var exp = {};
  23. // sets the timestamp for +uuid+ to now
  24. exp.update_timestamp = function(uuid) {
  25. console.log(uuid + " cache: updating timestamp");
  26. var time = new Date().getTime();
  27. redis.hmset(uuid, "t", time);
  28. };
  29. // create the key +uuid+, store +hash+ and time
  30. exp.save_hash = function(uuid, hash) {
  31. console.log(uuid + " cache: saving hash");
  32. var time = new Date().getTime();
  33. redis.hmset(uuid, "h", hash, "t", time);
  34. };
  35. // get a details object for +uuid+
  36. // {hash: "0123456789abcdef", time: 1414881524512}
  37. // null when uuid unkown
  38. exp.get_details = function(uuid, callback) {
  39. redis.hgetall(uuid, function(err, data) {
  40. callback(err, data);
  41. });
  42. };
  43. connect_redis();
  44. module.exports = exp;