comment.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { Types } from 'mongoose';
  2. import loggerFactory from '../../utils/logger';
  3. import { getModelSafely } from '../util/mongoose-utils';
  4. import ActivityDefine from '../util/activityDefine';
  5. import Crowi from '../crowi';
  6. const logger = loggerFactory('growi:service:CommentService');
  7. class CommentService {
  8. crowi!: Crowi;
  9. inAppNotificationService!: any;
  10. commentEvent!: any;
  11. constructor(crowi: Crowi) {
  12. this.crowi = crowi;
  13. this.inAppNotificationService = crowi.inAppNotificationService;
  14. this.commentEvent = crowi.event('comment');
  15. // init
  16. this.initCommentEventListeners();
  17. }
  18. initCommentEventListeners(): void {
  19. // create
  20. this.commentEvent.on('create', async(savedComment) => {
  21. try {
  22. const Page = getModelSafely('Page') || require('../models/page')(this.crowi);
  23. await Page.updateCommentCount(savedComment.page);
  24. const savedActivity = await this.createByPageComment(savedComment);
  25. let targetUsers: Types.ObjectId[] = [];
  26. targetUsers = await savedActivity.getNotificationTargetUsers();
  27. await this.inAppNotificationService.emitSocketIo(targetUsers);
  28. await this.inAppNotificationService.upsertByActivity(targetUsers, savedActivity);
  29. }
  30. catch (err) {
  31. logger.error('Error occurred while handling the comment create event:\n', err);
  32. }
  33. });
  34. // update
  35. this.commentEvent.on('update', (userId, pageId) => {
  36. this.commentEvent.onUpdate();
  37. // TODO: 79713
  38. // const { inAppNotificationService } = this.crowi;
  39. // inAppNotificationService.emitSocketIo(userId, pageId);
  40. });
  41. // remove
  42. this.commentEvent.on('remove', async(comment) => {
  43. this.commentEvent.onRemove();
  44. try {
  45. const Page = getModelSafely('Page') || require('../models/page')(this.crowi);
  46. await Page.updateCommentCount(comment.page);
  47. }
  48. catch (err) {
  49. logger.error('Error occurred while updating the comment count:\n', err);
  50. }
  51. });
  52. }
  53. /**
  54. * @param {Comment} comment
  55. * @return {Promise}
  56. */
  57. createByPageComment = function(comment) {
  58. const { activityService } = this.crowi;
  59. // TODO: Changing the action name in Create and Update
  60. const parameters = {
  61. user: comment.creator,
  62. targetModel: ActivityDefine.MODEL_PAGE,
  63. target: comment.page,
  64. eventModel: ActivityDefine.MODEL_COMMENT,
  65. event: comment._id,
  66. action: ActivityDefine.ACTION_COMMENT,
  67. };
  68. return activityService.createByParameters(parameters);
  69. };
  70. }
  71. module.exports = CommentService;