index.js 4.2 KB

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