cache.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. } else {
  10. redis = require("redis").createClient();
  11. }
  12. redis.on("ready", function() {
  13. console.log("Redis connection established.");
  14. redis.flushall();
  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. exp.get_redis = function() {
  25. return redis;
  26. };
  27. // sets the timestamp for +uuid+ to now
  28. exp.update_timestamp = function(uuid) {
  29. console.log(uuid + " cache: updating timestamp");
  30. var time = new Date().getTime();
  31. redis.hmset(uuid, "t", time);
  32. };
  33. // create the key +uuid+, store +hash+ and time
  34. exp.save_hash = function(uuid, hash) {
  35. console.log(uuid + " cache: saving hash");
  36. var time = new Date().getTime();
  37. redis.hmset(uuid, "h", hash, "t", time);
  38. };
  39. // get a details object for +uuid+
  40. // {hash: "0123456789abcdef", time: 1414881524512}
  41. // null when uuid unkown
  42. exp.get_details = function(uuid, callback) {
  43. redis.hgetall(uuid, function(err, data) {
  44. var details = null;
  45. if (data) {
  46. details = {
  47. hash: (data.h == "null" ? null : data.h),
  48. time: data.t
  49. };
  50. }
  51. callback(err, details);
  52. });
  53. };
  54. connect_redis();
  55. module.exports = exp;