comment.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { Types } from 'mongoose';
  2. import loggerFactory from '../../utils/logger';
  3. import { getModelSafely } from '../util/mongoose-utils';
  4. import { ActivityDocument } from '../models/activity';
  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 Activity = getModelSafely('Activity') || require('../models/activity')(this.crowi);
  27. const savedActivity = await Activity.createByPageComment(savedComment);
  28. let targetUsers: Types.ObjectId[] = [];
  29. targetUsers = await savedActivity.getNotificationTargetUsers();
  30. await this.inAppNotificationService.upsertByActivity(targetUsers, savedActivity);
  31. }
  32. catch (err) {
  33. logger.error('Error occurred while handling the comment create event:\n', err);
  34. }
  35. });
  36. // update
  37. this.commentEvent.on('update', (user) => {
  38. this.commentEvent.onUpdate();
  39. const { inAppNotificationService } = this.crowi;
  40. inAppNotificationService.emitSocketIo(user);
  41. });
  42. // remove
  43. this.commentEvent.on('remove', async(comment) => {
  44. this.commentEvent.onRemove();
  45. const { activityService } = this.crowi;
  46. try {
  47. const Page = getModelSafely('Page') || require('../models/page')(this.crowi);
  48. await Page.updateCommentCount(comment.page);
  49. }
  50. catch (err) {
  51. logger.error('Error occurred while updating the comment count:\n', err);
  52. }
  53. });
  54. }
  55. }
  56. module.exports = CommentService;