comment.ts 2.4 KB

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