index.js 6.1 KB

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