index.js 6.0 KB

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