notifications.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. const crypto = require('crypto');
  3. const redis = require('redis');
  4. let client = null;
  5. const subscriptions = [];
  6. const lib = {
  7. /**
  8. * Initializes the notifications module
  9. *
  10. * @param {String} url - the url of the redis server
  11. * @param {Function} cb - gets called once we're done initializing
  12. */
  13. init: (url, cb) => {
  14. client = redis.createClient({ url: url });
  15. client.on('error', (err) => console.error);
  16. client.on('message', (pattern, channel, expiredKey) => {
  17. subscriptions.forEach((sub) => {
  18. if (sub.name !== expiredKey) return;
  19. sub.cb();
  20. });
  21. });
  22. client.psubscribe('__keyevent@0__:expired');
  23. },
  24. /**
  25. * Schedules a notification to be dispatched in a specific amount of milliseconds,
  26. * notifications are unique by name, and the first one is always kept, as in
  27. * attempting to schedule a notification that already exists won't do anything
  28. *
  29. * @param {String} name - the name of the notification we want to schedule
  30. * @param {Integer} time - how long in milliseconds until the notification should be fired
  31. * @param {Function} cb - gets called when the notification has been scheduled
  32. */
  33. schedule: (name, time, cb) => {
  34. client.set(crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), '', 'PX', 'NX', time, cb);
  35. },
  36. /**
  37. * Subscribes a callback function to be called when a notification gets called
  38. *
  39. * @param {String} name - the name of the notification we want to subscribe to
  40. * @param {Function} cb - gets called when the subscribed notification gets called
  41. * @param {Boolean} unique - only subscribe if another subscription with the same name doesn't already exist
  42. * @return {Object} - the subscription object
  43. */
  44. subscribe: (name, cb, unique = false) => {
  45. if (unique && subscriptions.find((subscription) => subscription.name == name)) return;
  46. let subscription = { name: crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), cb };
  47. subscriptions.push(subscription);
  48. return subscription;
  49. },
  50. /**
  51. * Remove a notification subscription
  52. *
  53. * @param {Object} subscription - the subscription object returned by {@link subscribe}
  54. */
  55. remove: (subscription) => {
  56. let index = subscriptions.indexOf(subscription);
  57. if (index) subscriptions.splice(index, 1);
  58. }
  59. };
  60. module.exports = lib;