provider.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const EventEmitter = require('events');
  2. module.exports = function (dependencies) {
  3. const Client = dependencies.Client;
  4. function Provider(options) {
  5. if (false === this instanceof Provider) {
  6. return new Provider(options);
  7. }
  8. this.client = new Client(options);
  9. EventEmitter.call(this);
  10. }
  11. Provider.prototype = Object.create(EventEmitter.prototype);
  12. Provider.prototype.send = function send(notification, recipients) {
  13. const builtNotification = {
  14. headers: notification.headers(),
  15. body: notification.compile(),
  16. };
  17. if (!Array.isArray(recipients)) {
  18. recipients = [recipients];
  19. }
  20. return Promise.all(recipients.map(token => this.client.write(builtNotification, token))).then(
  21. responses => {
  22. const sent = [];
  23. const failed = [];
  24. responses.forEach(response => {
  25. if (response.status || response.error) {
  26. failed.push(response);
  27. } else {
  28. sent.push(response);
  29. }
  30. });
  31. return { sent, failed };
  32. }
  33. );
  34. };
  35. Provider.prototype.shutdown = function shutdown(callback) {
  36. this.client.shutdown(callback);
  37. };
  38. return Provider;
  39. };