index.js 4.7 KB

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