Просмотр исходного кода

Merge pull request #4489 from weseek/imprv/#79079-refuctoring-activity-model

Imprv/#79079 refuctoring activity model
Yuki Takei 4 лет назад
Родитель
Сommit
c49e91c74c

+ 11 - 2
packages/app/src/server/crowi/index.js

@@ -19,6 +19,8 @@ import AttachmentService from '../service/attachment';
 import { SlackIntegrationService } from '../service/slack-integration';
 import { SlackIntegrationService } from '../service/slack-integration';
 import { UserNotificationService } from '../service/user-notification';
 import { UserNotificationService } from '../service/user-notification';
 
 
+import Actiity from '../models/activity';
+
 const logger = loggerFactory('growi:crowi');
 const logger = loggerFactory('growi:crowi');
 const httpErrorHandler = require('../middlewares/http-error-handler');
 const httpErrorHandler = require('../middlewares/http-error-handler');
 
 
@@ -84,7 +86,6 @@ function Crowi() {
     tag: new (require('../events/tag'))(this),
     tag: new (require('../events/tag'))(this),
     admin: new (require('../events/admin'))(this),
     admin: new (require('../events/admin'))(this),
     comment: new (require('../events/comment'))(this),
     comment: new (require('../events/comment'))(this),
-    activity: new (require('../events/activity'))(),
   };
   };
 }
 }
 
 
@@ -300,7 +301,15 @@ Crowi.prototype.setupSocketIoService = async function() {
 };
 };
 
 
 Crowi.prototype.setupModels = async function() {
 Crowi.prototype.setupModels = async function() {
-  Object.keys(models).forEach((key) => {
+  let allModels = {};
+
+  // include models that dependent on crowi
+  allModels = models;
+
+  // include models that independent from crowi
+  allModels.Activity = Actiity;
+
+  Object.keys(allModels).forEach((key) => {
     return this.model(key, models[key](this));
     return this.model(key, models[key](this));
   });
   });
 };
 };

+ 3 - 2
packages/app/src/server/events/activity.ts

@@ -4,7 +4,7 @@ import loggerFactory from '../../utils/logger';
 const logger = loggerFactory('growi:events:activity');
 const logger = loggerFactory('growi:events:activity');
 
 
 
 
-export default class ActivityEvent extends EventEmitter {
+class ActivityEvent extends EventEmitter {
 
 
   onRemove(action: string, activity: any): void {
   onRemove(action: string, activity: any): void {
     logger.info('onRemove activity event fired');
     logger.info('onRemove activity event fired');
@@ -16,4 +16,5 @@ export default class ActivityEvent extends EventEmitter {
 
 
 }
 }
 
 
-module.exports = ActivityEvent;
+const instance = new ActivityEvent();
+export default instance;

+ 81 - 81
packages/app/src/server/models/activity.ts

@@ -1,11 +1,13 @@
 import {
 import {
   Types, Document, Model, Schema,
   Types, Document, Model, Schema,
 } from 'mongoose';
 } from 'mongoose';
-import Crowi from '../crowi';
 
 
-import { getOrCreateModel, getModelSafely } from '../util/mongoose-utils';
 import loggerFactory from '../../utils/logger';
 import loggerFactory from '../../utils/logger';
+
+import { getOrCreateModel, getModelSafely } from '../util/mongoose-utils';
+
 import ActivityDefine from '../util/activityDefine';
 import ActivityDefine from '../util/activityDefine';
+import activityEvent from '../events/activity';
 
 
 import Subscription from './subscription';
 import Subscription from './subscription';
 
 
@@ -27,87 +29,85 @@ export interface ActivityDocument extends Document {
 
 
 export type ActivityModel = Model<ActivityDocument>
 export type ActivityModel = Model<ActivityDocument>
 
 
-module.exports = function(crowi: Crowi) {
-  const activityEvent = crowi.event('activity');
-
-  // TODO: add revision id
-  const activitySchema = new Schema<ActivityDocument, ActivityModel>({
-    user: {
-      type: Schema.Types.ObjectId,
-      ref: 'User',
-      index: true,
-      require: true,
-    },
-    targetModel: {
-      type: String,
-      require: true,
-      enum: ActivityDefine.getSupportTargetModelNames(),
-    },
-    target: {
-      type: Schema.Types.ObjectId,
-      refPath: 'targetModel',
-      require: true,
-    },
-    action: {
-      type: String,
-      require: true,
-      enum: ActivityDefine.getSupportActionNames(),
-    },
-    event: {
-      type: Schema.Types.ObjectId,
-      refPath: 'eventModel',
-    },
-    eventModel: {
-      type: String,
-      enum: ActivityDefine.getSupportEventModelNames(),
-    },
-    createdAt: {
-      type: Date,
-      default: Date.now,
-    },
-  });
-  activitySchema.index({ target: 1, action: 1 });
-  activitySchema.index({
-    user: 1, target: 1, action: 1, createdAt: 1,
-  }, { unique: true });
-
-
-  activitySchema.methods.getNotificationTargetUsers = async function() {
-    const User = getModelSafely('User') || require('~/server/models/user')();
-    const { user: actionUser, targetModel, target } = this;
-
-    const model: any = await this.model(targetModel).findById(target);
-    const [targetUsers, subscribeUsers, unsubscribeUsers] = await Promise.all([
-      model.getNotificationTargetUsers(),
-      Subscription.getSubscription((target as any) as Types.ObjectId),
-      Subscription.getUnsubscription((target as any) as Types.ObjectId),
-    ]);
-
-    const unique = array => Object.values(array.reduce((objects, object) => ({ ...objects, [object.toString()]: object }), {}));
-    const filter = (array, pull) => {
-      const ids = pull.map(object => object.toString());
-      return array.filter(object => !ids.includes(object.toString()));
-    };
-    const notificationUsers = filter(unique([...targetUsers, ...subscribeUsers]), [...unsubscribeUsers, actionUser]);
-    const activeNotificationUsers = await User.find({
-      _id: { $in: notificationUsers },
-      status: User.STATUS_ACTIVE,
-    }).distinct('_id');
-    return activeNotificationUsers;
+
+// TODO: add revision id
+const activitySchema = new Schema<ActivityDocument, ActivityModel>({
+  user: {
+    type: Schema.Types.ObjectId,
+    ref: 'User',
+    index: true,
+    require: true,
+  },
+  targetModel: {
+    type: String,
+    require: true,
+    enum: ActivityDefine.getSupportTargetModelNames(),
+  },
+  target: {
+    type: Schema.Types.ObjectId,
+    refPath: 'targetModel',
+    require: true,
+  },
+  action: {
+    type: String,
+    require: true,
+    enum: ActivityDefine.getSupportActionNames(),
+  },
+  event: {
+    type: Schema.Types.ObjectId,
+    refPath: 'eventModel',
+  },
+  eventModel: {
+    type: String,
+    enum: ActivityDefine.getSupportEventModelNames(),
+  },
+  createdAt: {
+    type: Date,
+    default: Date.now,
+  },
+});
+activitySchema.index({ target: 1, action: 1 });
+activitySchema.index({
+  user: 1, target: 1, action: 1, createdAt: 1,
+}, { unique: true });
+
+
+activitySchema.methods.getNotificationTargetUsers = async function() {
+  const User = getModelSafely('User') || require('~/server/models/user')();
+  const { user: actionUser, targetModel, target } = this;
+
+  const model: any = await this.model(targetModel).findById(target);
+  const [targetUsers, subscribeUsers, unsubscribeUsers] = await Promise.all([
+    model.getNotificationTargetUsers(),
+    Subscription.getSubscription((target as any) as Types.ObjectId),
+    Subscription.getUnsubscription((target as any) as Types.ObjectId),
+  ]);
+
+  const unique = array => Object.values(array.reduce((objects, object) => ({ ...objects, [object.toString()]: object }), {}));
+  const filter = (array, pull) => {
+    const ids = pull.map(object => object.toString());
+    return array.filter(object => !ids.includes(object.toString()));
   };
   };
+  const notificationUsers = filter(unique([...targetUsers, ...subscribeUsers]), [...unsubscribeUsers, actionUser]);
+  const activeNotificationUsers = await User.find({
+    _id: { $in: notificationUsers },
+    status: User.STATUS_ACTIVE,
+  }).distinct('_id');
+  return activeNotificationUsers;
+};
 
 
-  activitySchema.post('save', async(savedActivity: ActivityDocument) => {
-    let targetUsers: Types.ObjectId[] = [];
-    try {
-      targetUsers = await savedActivity.getNotificationTargetUsers();
-    }
-    catch (err) {
-      logger.error(err);
-    }
 
 
-    activityEvent.emit('create', targetUsers, savedActivity);
-  });
+activitySchema.post('save', async(savedActivity: ActivityDocument) => {
+  let targetUsers: Types.ObjectId[] = [];
+  try {
+    targetUsers = await savedActivity.getNotificationTargetUsers();
+  }
+  catch (err) {
+    logger.error(err);
+  }
 
 
-  return getOrCreateModel<ActivityDocument, ActivityModel>('Activity', activitySchema);
+  activityEvent.emit('create', targetUsers, savedActivity);
+});
 
 
-};
+
+export default getOrCreateModel<ActivityDocument, ActivityModel>('Activity', activitySchema);

+ 0 - 1
packages/app/src/server/models/index.js

@@ -1,5 +1,4 @@
 module.exports = {
 module.exports = {
-  Activity: require('./activity'),
   Page: require('./page'),
   Page: require('./page'),
   // TODO GW-2746 bulk export pages
   // TODO GW-2746 bulk export pages
   // PageArchive: require('./page-archive'),
   // PageArchive: require('./page-archive'),

+ 1 - 3
packages/app/src/server/service/activity.ts

@@ -9,12 +9,9 @@ class ActivityService {
 
 
   inAppNotificationService!: any;
   inAppNotificationService!: any;
 
 
-  activityEvent!: any;
-
   constructor(crowi: Crowi) {
   constructor(crowi: Crowi) {
     this.crowi = crowi;
     this.crowi = crowi;
     this.inAppNotificationService = crowi.inAppNotificationService;
     this.inAppNotificationService = crowi.inAppNotificationService;
-    this.activityEvent = crowi.event('activity');
   }
   }
 
 
 
 
@@ -24,6 +21,7 @@ class ActivityService {
      */
      */
   createByParameters = function(parameters) {
   createByParameters = function(parameters) {
     const Activity = getModelSafely('Activity') || require('../models/activity')(this.crowi);
     const Activity = getModelSafely('Activity') || require('../models/activity')(this.crowi);
+
     return Activity.create(parameters);
     return Activity.create(parameters);
   };
   };
 
 

+ 0 - 3
packages/app/src/server/service/comment.ts

@@ -15,14 +15,11 @@ class CommentService {
 
 
   commentEvent!: any;
   commentEvent!: any;
 
 
-  activityEvent!: any;
-
   constructor(crowi: Crowi) {
   constructor(crowi: Crowi) {
     this.crowi = crowi;
     this.crowi = crowi;
     this.inAppNotificationService = crowi.inAppNotificationService;
     this.inAppNotificationService = crowi.inAppNotificationService;
 
 
     this.commentEvent = crowi.event('comment');
     this.commentEvent = crowi.event('comment');
-    this.activityEvent = crowi.event('activity');
 
 
     // init
     // init
     this.initCommentEventListeners();
     this.initCommentEventListeners();

+ 0 - 3
packages/app/src/server/service/in-app-notification.ts

@@ -20,13 +20,10 @@ export default class InAppNotificationService {
 
 
   commentEvent!: any;
   commentEvent!: any;
 
 
-  activityEvent!: any;
-
 
 
   constructor(crowi: Crowi) {
   constructor(crowi: Crowi) {
     this.crowi = crowi;
     this.crowi = crowi;
     this.socketIoService = crowi.socketIoService;
     this.socketIoService = crowi.socketIoService;
-    this.activityEvent = crowi.event('activity');
 
 
     this.getUnreadCountByUser = this.getUnreadCountByUser.bind(this);
     this.getUnreadCountByUser = this.getUnreadCountByUser.bind(this);
   }
   }