notifications.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. console.log(time);
  38. pub.set(crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), '', 'PX', time, 'NX', cb);
  39. },
  40. /**
  41. * Subscribes a callback function to be called when a notification gets called
  42. *
  43. * @param {String} name - the name of the notification we want to subscribe to
  44. * @param {Function} cb - gets called when the subscribed notification gets called
  45. * @param {Boolean} unique - only subscribe if another subscription with the same name doesn't already exist
  46. * @return {Object} - the subscription object
  47. */
  48. subscribe: (name, cb, unique = false) => {
  49. if (unique && subscriptions.find((subscription) => subscription.name == name)) return;
  50. let subscription = { name: crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), cb };
  51. subscriptions.push(subscription);
  52. return subscription;
  53. },
  54. /**
  55. * Remove a notification subscription
  56. *
  57. * @param {Object} subscription - the subscription object returned by {@link subscribe}
  58. */
  59. remove: (subscription) => {
  60. let index = subscriptions.indexOf(subscription);
  61. if (index) subscriptions.splice(index, 1);
  62. }
  63. };
  64. module.exports = lib;