index.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. 'use strict';
  2. const redis = require('redis');
  3. // Lightweight / convenience wrapper around redis module for our needs
  4. const pubs = {}, subs = {};
  5. const lib = {
  6. client: null,
  7. url: '',
  8. schemas: {
  9. session: require('./schemas/session'),
  10. userSession: require('./schemas/userSession'),
  11. station: require('./schemas/station'),
  12. song: require('./schemas/song')
  13. },
  14. /**
  15. * Initializes the cache module
  16. *
  17. * @param {String} url - the url of the redis server
  18. * @param {Function} cb - gets called once we're done initializing
  19. */
  20. init: (url, cb) => {
  21. lib.url = url;
  22. lib.client = redis.createClient({ url: lib.url });
  23. lib.client.on('error', (err) => console.error);
  24. cb();
  25. },
  26. /**
  27. * Gracefully closes all the Redis client connections
  28. */
  29. quit: () => {
  30. lib.client.quit();
  31. Object.keys(pubs).forEach((channel) => pubs[channel].quit());
  32. Object.keys(subs).forEach((channel) => subs[channel].client.quit());
  33. },
  34. /**
  35. * Sets a single value in a table
  36. *
  37. * @param {String} table - name of the table we want to set a key of (table === redis hash)
  38. * @param {String} key - name of the key to set
  39. * @param {*} value - the value we want to set
  40. * @param {Function} cb - gets called when the value has been set in Redis
  41. * @param {Boolean} [stringifyJson=true] - stringify 'value' if it's an Object or Array
  42. */
  43. hset: (table, key, value, cb, stringifyJson = true) => {
  44. // automatically stringify objects and arrays into JSON
  45. if (stringifyJson && ['object', 'array'].includes(typeof value)) value = JSON.stringify(value);
  46. lib.client.hset(table, key, value, err => {
  47. if (cb !== undefined) {
  48. if (err) return cb(err);
  49. cb(null);
  50. }
  51. });
  52. },
  53. /**
  54. * Gets a single value from a table
  55. *
  56. * @param {String} table - name of the table to get the value from (table === redis hash)
  57. * @param {String} key - name of the key to fetch
  58. * @param {Function} cb - gets called when the value is returned from Redis
  59. * @param {Boolean} [parseJson=true] - attempt to parse returned data as JSON
  60. */
  61. hget: (table, key, cb, parseJson = true) => {
  62. lib.client.hget(table, key, (err, value) => {
  63. if (err) return typeof cb === 'function' ? cb(err) : null;
  64. if (parseJson) try { value = JSON.parse(value); } catch (e) {}
  65. if (typeof cb === 'function') cb(null, value);
  66. });
  67. },
  68. /**
  69. * Deletes a single value from a table
  70. *
  71. * @param {String} table - name of the table to delete the value from (table === redis hash)
  72. * @param {String} key - name of the key to delete
  73. * @param {Function} cb - gets called when the value has been deleted from Redis or when it returned an error
  74. */
  75. hdel: (table, key, cb) => {
  76. lib.client.hdel(table, key, (err) => {
  77. if (err) return typeof cb === 'function' ? cb(err) : null;
  78. if (typeof cb === 'function') cb(null);
  79. });
  80. },
  81. /**
  82. * Returns all the keys for a table
  83. *
  84. * @param {String} table - name of the table to get the values from (table === redis hash)
  85. * @param {Function} cb - gets called when the values are returned from Redis
  86. * @param {Boolean} [parseJson=true] - attempts to parse all values as JSON by default
  87. */
  88. hgetall: (table, cb, parseJson = true) => {
  89. lib.client.hgetall(table, (err, obj) => {
  90. if (err) return typeof cb === 'function' ? cb(err) : null;
  91. if (parseJson && obj) Object.keys(obj).forEach((key) => { try { obj[key] = JSON.parse(obj[key]); } catch (e) {} });
  92. cb(null, obj);
  93. });
  94. },
  95. /**
  96. * Publish a message to a channel, caches the redis client connection
  97. *
  98. * @param {String} channel - the name of the channel we want to publish a message to
  99. * @param {*} value - the value we want to send
  100. * @param {Boolean} [stringifyJson=true] - stringify 'value' if it's an Object or Array
  101. */
  102. pub: (channel, value, stringifyJson = true) => {
  103. if (pubs[channel] === undefined) {
  104. pubs[channel] = redis.createClient({ url: lib.url });
  105. pubs[channel].on('error', (err) => console.error);
  106. }
  107. if (stringifyJson && ['object', 'array'].includes(typeof value)) value = JSON.stringify(value);
  108. pubs[channel].publish(channel, value);
  109. },
  110. /**
  111. * Subscribe to a channel, caches the redis client connection
  112. *
  113. * @param {String} channel - name of the channel to subscribe to
  114. * @param {Function} cb - gets called when a message is received
  115. * @param {Boolean} [parseJson=true] - parse the message as JSON
  116. */
  117. sub: (channel, cb, parseJson = true) => {
  118. if (subs[channel] === undefined) {
  119. subs[channel] = { client: redis.createClient({ url: lib.url }), cbs: [] };
  120. subs[channel].client.on('error', (err) => console.error);
  121. subs[channel].client.on('message', (channel, message) => {
  122. if (parseJson) try { message = JSON.parse(message); } catch (e) {}
  123. subs[channel].cbs.forEach((cb) => cb(message));
  124. });
  125. subs[channel].client.subscribe(channel);
  126. }
  127. subs[channel].cbs.push(cb);
  128. }
  129. };
  130. module.exports = lib;