comment.ts 2.4 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. activityEvent!: any;
  12. constructor(crowi: Crowi) {
  13. this.crowi = crowi;
  14. this.inAppNotificationService = crowi.inAppNotificationService;
  15. this.commentEvent = crowi.event('comment');
  16. this.activityEvent = crowi.event('activity');
  17. // init
  18. this.initCommentEventListeners();
  19. }
  20. initCommentEventListeners(): void {
  21. // create
  22. this.commentEvent.on('create', async(savedComment) => {
  23. try {
  24. const Page = getModelSafely('Page') || require('../models/page')(this.crowi);
  25. await Page.updateCommentCount(savedComment.page);
  26. const savedActivity = await this.createByPageComment(savedComment);
  27. let targetUsers: Types.ObjectId[] = [];
  28. targetUsers = await savedActivity.getNotificationTargetUsers();
  29. await this.inAppNotificationService.upsertByActivity(targetUsers, savedActivity);
  30. }
  31. catch (err) {
  32. logger.error('Error occurred while handling the comment create event:\n', err);
  33. }
  34. });
  35. // update
  36. this.commentEvent.on('update', (user) => {
  37. this.commentEvent.onUpdate();
  38. const { inAppNotificationService } = this.crowi;
  39. inAppNotificationService.emitSocketIo(user);
  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;