index.js 6.7 KB

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