index.js 5.8 KB

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