pre-notify.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { getIdForRef, type IPage, type IUser, type Ref } from '@growi/core';
  2. import mongoose from 'mongoose';
  3. import type { ActivityDocument } from '../models/activity';
  4. import Subscription from '../models/subscription';
  5. export type PreNotifyProps = {
  6. notificationTargetUsers?: Ref<IUser>[];
  7. };
  8. export type PreNotify = (props: PreNotifyProps) => Promise<void>;
  9. export type GetAdditionalTargetUsers = (
  10. activity: ActivityDocument,
  11. ) => Promise<Ref<IUser>[]>;
  12. export type GeneratePreNotify = (
  13. activity: ActivityDocument,
  14. getAdditionalTargetUsers?: GetAdditionalTargetUsers,
  15. ) => PreNotify;
  16. interface IPreNotifyService {
  17. generateInitialPreNotifyProps: (PreNotifyProps) => {
  18. notificationTargetUsers?: Ref<IUser>[];
  19. };
  20. generatePreNotify: GeneratePreNotify;
  21. }
  22. class PreNotifyService implements IPreNotifyService {
  23. generateInitialPreNotifyProps = (): PreNotifyProps => {
  24. const initialPreNotifyProps: Ref<IUser>[] = [];
  25. return { notificationTargetUsers: initialPreNotifyProps };
  26. };
  27. generatePreNotify = (
  28. activity: ActivityDocument,
  29. getAdditionalTargetUsers?: GetAdditionalTargetUsers,
  30. ): PreNotify => {
  31. const preNotify = async (props: PreNotifyProps) => {
  32. const { notificationTargetUsers } = props;
  33. const User = mongoose.model<IUser, { find; STATUS_ACTIVE }>('User');
  34. const actionUser = activity.user;
  35. const target = activity.target;
  36. const subscribedUsers = await Subscription.getSubscription(
  37. target as unknown as Ref<IPage>,
  38. );
  39. const notificationUsers = subscribedUsers.filter(
  40. (item) => item.toString() !== getIdForRef(actionUser).toString(),
  41. );
  42. const activeNotificationUsers = await User.find({
  43. _id: { $in: notificationUsers },
  44. status: User.STATUS_ACTIVE,
  45. }).distinct('_id');
  46. if (getAdditionalTargetUsers == null) {
  47. notificationTargetUsers?.push(...activeNotificationUsers);
  48. } else {
  49. const AdditionalTargetUsers = await getAdditionalTargetUsers(activity);
  50. notificationTargetUsers?.push(
  51. ...activeNotificationUsers,
  52. ...AdditionalTargetUsers,
  53. );
  54. }
  55. };
  56. return preNotify;
  57. };
  58. }
  59. export const preNotifyService = new PreNotifyService();