notifications.js 2.5 KB

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