index.js 5.7 KB

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