index.js 5.6 KB

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