comment.ts 2.5 KB

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