index.js 5.0 KB

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