cache.js 1.3 KB

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