index.js 5.4 KB

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