index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const toArrayFromCsv = require('@commons/util/to-array-from-csv');
  2. /**
  3. * service class of UserNotification
  4. */
  5. class UserNotificationService {
  6. constructor(crowi) {
  7. this.crowi = crowi;
  8. this.Page = this.crowi.model('Page');
  9. }
  10. /**
  11. * fire user notification
  12. *
  13. * @memberof UserNotificationService
  14. *
  15. * @param {Page} page
  16. * @param {User} user
  17. * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
  18. * @param {string} mode 'create' or 'update' or 'comment'
  19. * @param {string} previousRevision
  20. * @param {Comment} comment
  21. */
  22. async fire(page, user, slackChannelsStr, mode, previousRevision = '', comment = {}) {
  23. const { slackNotificationService, slack } = this.crowi;
  24. await page.updateSlackChannels(slackChannelsStr);
  25. if (!slackNotificationService.hasSlackConfig()) {
  26. throw new Error('slackNotificationService has not been set up');
  27. }
  28. // "dev,slacktest" => [dev,slacktest]
  29. const slackChannels = toArrayFromCsv(slackChannelsStr);
  30. const promises = slackChannels.map(async(chan) => {
  31. let res;
  32. if (mode === 'comment') {
  33. res = await slack.postComment(comment, user, chan, page.path);
  34. }
  35. else {
  36. res = await slack.postPage(page, user, chan, mode, previousRevision);
  37. }
  38. if (res.status !== 'ok') {
  39. throw new Error(`fail to send slack notification to #${chan} channel`);
  40. }
  41. return res;
  42. });
  43. return Promise.allSettled(promises);
  44. }
  45. }
  46. module.exports = UserNotificationService;