index.js 6.0 KB

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