index.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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 (cb !== undefined) {
  46. if (err) return cb(err);
  47. cb(null);
  48. }
  49. });
  50. },
  51. /**
  52. * Gets a single value from a table
  53. *
  54. * @param {String} table - name of the table to get the value from (table === redis hash)
  55. * @param {String} key - name of the key to fetch
  56. * @param {Function} cb - gets called when the value is returned from Redis
  57. * @param {Boolean} [parseJson=true] - attempt to parse returned data as JSON
  58. */
  59. hget: (table, key, cb, parseJson = true) => {
  60. lib.client.hget(table, key, (err, value) => {
  61. if (err) return typeof cb === 'function' ? cb(err) : null;
  62. if (parseJson) try { value = JSON.parse(value); } catch (e) {}
  63. if (typeof cb === 'function') cb(null, value);
  64. });
  65. },
  66. /**
  67. * Returns all the keys for a table
  68. *
  69. * @param {String} table - name of the table to get the values from (table === redis hash)
  70. * @param {Function} cb - gets called when the values are returned from Redis
  71. * @param {Boolean} [parseJson=true] - attempts to parse all values as JSON by default
  72. */
  73. hgetall: (table, cb, parseJson = true) => {
  74. lib.client.hgetall(table, (err, obj) => {
  75. if (err) return typeof cb === 'function' ? cb(err) : null;
  76. if (parseJson) Object.keys(obj).forEach((key) => { try { obj[key] = JSON.parse(obj[key]); } catch (e) {} });
  77. cb(null, obj);
  78. });
  79. },
  80. /**
  81. * Publish a message to a channel, caches the redis client connection
  82. *
  83. * @param {String} channel - the name of the channel we want to publish a message to
  84. * @param {*} value - the value we want to send
  85. * @param {Boolean} [stringifyJson=true] - stringify 'value' if it's an Object or Array
  86. */
  87. pub: (channel, value, stringifyJson = true) => {
  88. if (pubs[channel] === undefined) {
  89. pubs[channel] = redis.createClient({ url: lib.url });
  90. pubs[channel].on('error', (err) => console.error);
  91. }
  92. if (stringifyJson && ['object', 'array'].includes(typeof value)) value = JSON.stringify(value);
  93. pubs[channel].publish(channel, value);
  94. },
  95. /**
  96. * Subscribe to a channel, caches the redis client connection
  97. *
  98. * @param {String} channel - name of the channel to subscribe to
  99. * @param {Function} cb - gets called when a message is received
  100. * @param {Boolean} [parseJson=true] - parse the message as JSON
  101. */
  102. sub: (channel, cb, parseJson = true) => {
  103. if (subs[channel] === undefined) {
  104. subs[channel] = { client: redis.createClient({ url: lib.url }), cbs: [] };
  105. subs[channel].client.on('error', (err) => console.error);
  106. subs[channel].client.on('message', (channel, message) => {
  107. if (parseJson) try { message = JSON.parse(message); } catch (e) {}
  108. subs[channel].cbs.forEach((cb) => cb(message));
  109. });
  110. subs[channel].subscribe(channel);
  111. }
  112. subs[channel].cbs.push(cb);
  113. }
  114. };
  115. module.exports = lib;