index.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import config from "config";
  2. import redis from "redis";
  3. import mongoose from "mongoose";
  4. import CoreClass from "../../core";
  5. // Lightweight / convenience wrapper around redis module for our needs
  6. const pubs = {};
  7. const subs = {};
  8. let CacheModule;
  9. class _CacheModule extends CoreClass {
  10. // eslint-disable-next-line require-jsdoc
  11. constructor() {
  12. super("cache");
  13. CacheModule = this;
  14. }
  15. /**
  16. * Initialises the cache/redis module
  17. *
  18. * @returns {Promise} - returns promise (reject, resolve)
  19. */
  20. async initialize() {
  21. const importSchema = schemaName =>
  22. new Promise(resolve => {
  23. import(`./schemas/${schemaName}`).then(schema => resolve(schema.default));
  24. });
  25. this.schemas = {
  26. session: await importSchema("session"),
  27. station: await importSchema("station"),
  28. playlist: await importSchema("playlist"),
  29. officialPlaylist: await importSchema("officialPlaylist"),
  30. song: await importSchema("song"),
  31. punishment: await importSchema("punishment"),
  32. recentActivity: await importSchema("recentActivity")
  33. };
  34. return new Promise((resolve, reject) => {
  35. this.url = config.get("redis").url;
  36. this.password = config.get("redis").password;
  37. this.log("INFO", "Connecting...");
  38. this.client = redis.createClient({
  39. url: this.url,
  40. password: this.password,
  41. retry_strategy: options => {
  42. if (this.getStatus() === "LOCKDOWN") return;
  43. if (this.getStatus() !== "RECONNECTING") this.setStatus("RECONNECTING");
  44. this.log("INFO", `Attempting to reconnect.`);
  45. if (options.attempt >= 10) {
  46. this.log("ERROR", `Stopped trying to reconnect.`);
  47. this.setStatus("FAILED");
  48. // this.failed = true;
  49. // this._lockdown();
  50. }
  51. }
  52. });
  53. this.client.on("error", err => {
  54. if (this.getStatus() === "INITIALIZING") reject(err);
  55. if (this.getStatus() === "LOCKDOWN") return;
  56. this.log("ERROR", `Error ${err.message}.`);
  57. });
  58. this.client.on("connect", () => {
  59. this.log("INFO", "Connected succesfully.");
  60. if (this.getStatus() === "INITIALIZING") resolve();
  61. else if (this.getStatus() === "FAILED" || this.getStatus() === "RECONNECTING") this.setStatus("READY");
  62. });
  63. });
  64. }
  65. /**
  66. * Quits redis client
  67. *
  68. * @returns {Promise} - returns promise (reject, resolve)
  69. */
  70. QUIT() {
  71. return new Promise(resolve => {
  72. if (CacheModule.client.connected) {
  73. CacheModule.client.quit();
  74. Object.keys(pubs).forEach(channel => pubs[channel].quit());
  75. Object.keys(subs).forEach(channel => subs[channel].client.quit());
  76. }
  77. resolve();
  78. });
  79. }
  80. /**
  81. * Sets a single value in a table
  82. *
  83. * @param {object} payload - object containing payload
  84. * @param {string} payload.table - name of the table we want to set a key of (table === redis hash)
  85. * @param {string} payload.key - name of the key to set
  86. * @param {*} payload.value - the value we want to set
  87. * @param {boolean} [payload.stringifyJson=true] - stringify 'value' if it's an Object or Array
  88. * @returns {Promise} - returns a promise (resolve, reject)
  89. */
  90. HSET(payload) {
  91. return new Promise((resolve, reject) => {
  92. let { key } = payload;
  93. let { value } = payload;
  94. if (mongoose.Types.ObjectId.isValid(key)) key = key.toString();
  95. // automatically stringify objects and arrays into JSON
  96. if (["object", "array"].includes(typeof value)) value = JSON.stringify(value);
  97. CacheModule.client.hset(payload.table, key, value, err => {
  98. if (err) return reject(new Error(err));
  99. return resolve(JSON.parse(value));
  100. });
  101. });
  102. }
  103. /**
  104. * Gets a single value from a table
  105. *
  106. * @param {object} payload - object containing payload
  107. * @param {string} payload.table - name of the table to get the value from (table === redis hash)
  108. * @param {string} payload.key - name of the key to fetch
  109. * @param {boolean} [payload.parseJson=true] - attempt to parse returned data as JSON
  110. * @returns {Promise} - returns a promise (resolve, reject)
  111. */
  112. HGET(payload) {
  113. return new Promise((resolve, reject) => {
  114. let { key } = payload;
  115. if (!key) return reject(new Error("Invalid key!"));
  116. if (!payload.table) return reject(new Error("Invalid table!"));
  117. if (mongoose.Types.ObjectId.isValid(key)) key = key.toString();
  118. return CacheModule.client.hget(payload.table, key, (err, value) => {
  119. if (err) return reject(new Error(err));
  120. try {
  121. value = JSON.parse(value);
  122. } catch (e) {
  123. return reject(err);
  124. }
  125. return resolve(value);
  126. });
  127. });
  128. }
  129. /**
  130. * Deletes a single value from a table
  131. *
  132. * @param {object} payload - object containing payload
  133. * @param {string} payload.table - name of the table to delete the value from (table === redis hash)
  134. * @param {string} payload.key - name of the key to delete
  135. * @returns {Promise} - returns a promise (resolve, reject)
  136. */
  137. HDEL(payload) {
  138. return new Promise((resolve, reject) => {
  139. // if (!payload.key || !table || typeof key !== "string")
  140. // return cb(null, null);
  141. let { key } = payload;
  142. if (!payload.table) return reject(new Error("Invalid table!"));
  143. if (!key) return reject(new Error("Invalid key!"));
  144. if (mongoose.Types.ObjectId.isValid(key)) key = key.toString();
  145. return CacheModule.client.hdel(payload.table, key, err => {
  146. if (err) return reject(new Error(err));
  147. return resolve();
  148. });
  149. });
  150. }
  151. /**
  152. * Returns all the keys for a table
  153. *
  154. * @param {object} payload - object containing payload
  155. * @param {string} payload.table - name of the table to get the values from (table === redis hash)
  156. * @param {boolean} [payload.parseJson=true] - attempts to parse all values as JSON by default
  157. * @returns {Promise} - returns a promise (resolve, reject)
  158. */
  159. HGETALL(payload) {
  160. return new Promise((resolve, reject) => {
  161. if (!payload.table) return reject(new Error("Invalid table!"));
  162. return CacheModule.client.hgetall(payload.table, (err, obj) => {
  163. if (err) return reject(new Error(err));
  164. if (obj)
  165. Object.keys(obj).forEach(key => {
  166. obj[key] = JSON.parse(obj[key]);
  167. });
  168. else if (!obj) obj = [];
  169. return resolve(obj);
  170. });
  171. });
  172. }
  173. /**
  174. * Publish a message to a channel, caches the redis client connection
  175. *
  176. * @param {object} payload - object containing payload
  177. * @param {string} payload.channel - the name of the channel we want to publish a message to
  178. * @param {*} payload.value - the value we want to send
  179. * @param {boolean} [payload.stringifyJson=true] - stringify 'value' if it's an Object or Array
  180. * @returns {Promise} - returns a promise (resolve, reject)
  181. */
  182. PUB(payload) {
  183. return new Promise((resolve, reject) => {
  184. /* if (pubs[channel] === undefined) {
  185. pubs[channel] = redis.createClient({ url: CacheModule.url });
  186. pubs[channel].on('error', (err) => console.error);
  187. } */
  188. let { value } = payload;
  189. if (!payload.channel) return reject(new Error("Invalid channel!"));
  190. if (!value) return reject(new Error("Invalid value!"));
  191. if (["object", "array"].includes(typeof value)) value = JSON.stringify(value);
  192. // pubs[channel].publish(channel, value);
  193. return CacheModule.client.publish(payload.channel, value, err => {
  194. if (err) reject(err);
  195. else resolve();
  196. });
  197. });
  198. }
  199. /**
  200. * Subscribe to a channel, caches the redis client connection
  201. *
  202. * @param {object} payload - object containing payload
  203. * @param {string} payload.channel - name of the channel to subscribe to
  204. * @param {boolean} [payload.parseJson=true] - parse the message as JSON
  205. * @returns {Promise} - returns a promise (resolve, reject)
  206. */
  207. SUB(payload) {
  208. return new Promise((resolve, reject) => {
  209. if (!payload.channel) return reject(new Error("Invalid channel!"));
  210. if (subs[payload.channel] === undefined) {
  211. subs[payload.channel] = {
  212. client: redis.createClient({
  213. url: CacheModule.url,
  214. password: CacheModule.password
  215. }),
  216. cbs: []
  217. };
  218. subs[payload.channel].client.on("message", (channel, message) => {
  219. if (message.startsWith("[") || message.startsWith("{"))
  220. try {
  221. message = JSON.parse(message);
  222. } catch (err) {
  223. console.error(err);
  224. }
  225. else if (message.startsWith('"') && message.endsWith('"'))
  226. message = message.substring(1).substring(0, message.length - 2);
  227. return subs[channel].cbs.forEach(cb => cb(message));
  228. });
  229. subs[payload.channel].client.subscribe(payload.channel);
  230. }
  231. subs[payload.channel].cbs.push(payload.cb);
  232. return resolve();
  233. });
  234. }
  235. /**
  236. * Returns a redis schema
  237. *
  238. * @param {object} payload - object containing the payload
  239. * @param {string} payload.schemaName - the name of the schema to get
  240. * @returns {Promise} - returns promise (reject, resolve)
  241. */
  242. GET_SCHEMA(payload) {
  243. return new Promise(resolve => {
  244. resolve(CacheModule.schemas[payload.schemaName]);
  245. });
  246. }
  247. }
  248. export default new _CacheModule();