index.js 4.2 KB

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