comment.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. const parameters = {
  60. user: comment.creator,
  61. targetModel: ActivityDefine.MODEL_PAGE,
  62. target: comment.page,
  63. eventModel: ActivityDefine.MODEL_COMMENT,
  64. event: comment._id,
  65. action: ActivityDefine.ACTION_COMMENT,
  66. };
  67. return activityService.createByParameters(parameters);
  68. };
  69. }
  70. module.exports = CommentService;