comment.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { Types } from 'mongoose';
  2. import loggerFactory from '../../utils/logger';
  3. import Crowi from '../crowi';
  4. import { getModelSafely } from '../util/mongoose-utils';
  5. // https://regex101.com/r/Ztxj2j/1
  6. const USERNAME_PATTERN = new RegExp(/\B@[\w@.-]+/g);
  7. const logger = loggerFactory('growi:service:CommentService');
  8. class CommentService {
  9. crowi!: Crowi;
  10. activityService!: any;
  11. inAppNotificationService!: any;
  12. commentEvent!: any;
  13. constructor(crowi: Crowi) {
  14. this.crowi = crowi;
  15. this.activityService = crowi.activityService;
  16. this.inAppNotificationService = crowi.inAppNotificationService;
  17. this.commentEvent = crowi.event('comment');
  18. // init
  19. this.initCommentEventListeners();
  20. }
  21. initCommentEventListeners(): void {
  22. // create
  23. this.commentEvent.on('create', async(savedComment) => {
  24. try {
  25. const Page = getModelSafely('Page') || require('../models/page')(this.crowi);
  26. await Page.updateCommentCount(savedComment.page);
  27. }
  28. catch (err) {
  29. logger.error('Error occurred while handling the comment create event:\n', err);
  30. }
  31. });
  32. // update
  33. this.commentEvent.on('update', async() => {
  34. try {
  35. this.commentEvent.onUpdate();
  36. }
  37. catch (err) {
  38. logger.error('Error occurred while handling the comment update event:\n', err);
  39. }
  40. });
  41. // remove
  42. this.commentEvent.on('delete', async(removedComment) => {
  43. this.commentEvent.onDelete();
  44. try {
  45. const Page = getModelSafely('Page') || require('../models/page')(this.crowi);
  46. await Page.updateCommentCount(removedComment.page);
  47. }
  48. catch (err) {
  49. logger.error('Error occurred while updating the comment count:\n', err);
  50. }
  51. });
  52. }
  53. getMentionedUsers = async(commentId: Types.ObjectId): Promise<Types.ObjectId[]> => {
  54. const Comment = getModelSafely('Comment') || require('../models/comment')(this.crowi);
  55. const User = getModelSafely('User') || require('../models/user')(this.crowi);
  56. // Get comment by comment ID
  57. const commentData = await Comment.findOne({ _id: commentId });
  58. const { comment } = commentData;
  59. const usernamesFromComment = comment.match(USERNAME_PATTERN);
  60. // Get username from comment and remove duplicate username
  61. const mentionedUsernames = [...new Set(usernamesFromComment?.map((username) => {
  62. return username.slice(1);
  63. }))];
  64. // Get mentioned users ID
  65. const mentionedUserIDs = await User.find({ username: { $in: mentionedUsernames } });
  66. return mentionedUserIDs?.map((user) => {
  67. return user._id;
  68. });
  69. };
  70. }
  71. module.exports = CommentService;