index.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. 'use strict';
  2. // Lightweight / convenience wrapper around redis module for our needs
  3. const pubs = {}, subs = {};
  4. const lib = {
  5. client: null,
  6. url: '',
  7. schemas: {
  8. session: require('./schemas/session'),
  9. station: require('./schemas/station')
  10. },
  11. /**
  12. * Initializes the cache module
  13. *
  14. * @param {String} url - the url of the redis server
  15. * @param {Function} cb - gets called once we're done initializing
  16. */
  17. init: (url, cb) => {
  18. lib.url = url;
  19. lib.client = redis.createClient({ url: lib.url });
  20. lib.client.on('error', (err) => console.error);
  21. cb();
  22. },
  23. /**
  24. * Gracefully closes all the Redis client connections
  25. */
  26. quit: () => {
  27. lib.client.quit();
  28. Object.keys(pubs).forEach((channel) => pubs[channel].quit());
  29. Object.keys(subs).forEach((channel) => subs[channel].client.quit());
  30. },
  31. /**
  32. * Sets a single value in a table
  33. *
  34. * @param {String} table - name of the table we want to set a key of (table === redis hash)
  35. * @param {String} key - name of the key to set
  36. * @param {*} value - the value we want to set
  37. * @param {Function} cb - gets called when the value has been set in Redis
  38. * @param {Boolean} [stringifyJson=true] - stringify 'value' if it's an Object or Array
  39. */
  40. hset: (table, key, value, cb, stringifyJson = true) => {
  41. // automatically stringify objects and arrays into JSON
  42. if (stringifyJson && ['object', 'array'].includes(typeof value)) value = JSON.stringify(value);
  43. lib.client.hset(table, key, value, (err) => {
  44. if (err) return cb(err);
  45. cb(null);
  46. });
  47. },
  48. /**
  49. * Gets a single value from a table
  50. *
  51. * @param {String} table - name of the table to get the value from (table === redis hash)
  52. * @param {String} key - name of the key to fetch
  53. * @param {Function} cb - gets called when the value is returned from Redis
  54. * @param {Boolean} [parseJson=true] - attempt to parse returned data as JSON
  55. */
  56. hget: (table, key, cb, parseJson = true) => {
  57. lib.client.hget(table, key, (err, value) => {
  58. if (err) return typeof cb === 'function' ? cb(err) : null;
  59. if (parseJson) try { value = JSON.parse(value); } catch (e) {}
  60. if (typeof cb === 'function') cb(null, value);
  61. });
  62. },
  63. /**
  64. * Returns all the keys for a table
  65. *
  66. * @param {String} table - name of the table to get the values from (table === redis hash)
  67. * @param {Function} cb - gets called when the values are returned from Redis
  68. * @param {Boolean} [parseJson=true] - attempts to parse all values as JSON by default
  69. */
  70. hgetall: (table, cb, parseJson = true) => {
  71. lib.client.hgetall(table, (err, obj) => {
  72. if (err) return typeof cb === 'function' ? cb(err) : null;
  73. if (parseJson) Object.keys(obj).forEach((key) => { try { obj[key] = JSON.parse(obj[key]); } catch (e) {} });
  74. cb(null, obj);
  75. });
  76. },
  77. /**
  78. * Publish a message to a channel, caches the redis client connection
  79. *
  80. * @param {String} channel - the name of the channel we want to publish a message to
  81. * @param {*} value - the value we want to send
  82. * @param {Boolean} [stringifyJson=true] - stringify 'value' if it's an Object or Array
  83. */
  84. pub: (channel, value, stringifyJson = true) => {
  85. if (pubs[channel] === undefined) {
  86. pubs[channel] = redis.createClient({ url: lib.url });
  87. pubs[channel].on('error', (err) => console.error);
  88. }
  89. if (stringifyJson && ['object', 'array'].includes(typeof value)) value = JSON.stringify(value);
  90. pubs[channel].publish(channel, value);
  91. },
  92. /**
  93. * Subscribe to a channel, caches the redis client connection
  94. *
  95. * @param {String} channel - name of the channel to subscribe to
  96. * @param {Function} cb - gets called when a message is received
  97. * @param {Boolean} [parseJson=true] - parse the message as JSON
  98. */
  99. sub: (channel, cb, parseJson = true) => {
  100. if (subs[channel] === undefined) {
  101. subs[channel] = { client: redis.createClient({ url: lib.url }), cbs: [] };
  102. subs[channel].client.on('error', (err) => console.error);
  103. subs[channel].client.on('message', (channel, message) => {
  104. if (parseJson) try { message = JSON.parse(message); } catch (e) {}
  105. subs[channel].cbs.forEach((cb) => cb(message));
  106. });
  107. subs[channel].subscribe(channel);
  108. }
  109. subs[channel].cbs.push(cb);
  110. }
  111. };
  112. module.exports = lib;