Browse Source

refactor: improve readability by restructuring async route handlers and simplifying code

reiji-h 1 year ago
parent
commit
42e1102a64

+ 37 - 36
apps/app/src/server/routes/apiv3/attachment.js

@@ -199,45 +199,46 @@ module.exports = (crowi) => {
    *                  type: object
    *                  $ref: '#/components/schemas/AttachmentPaginateResult'
    */
-  router.get('/list', accessTokenParser([SCOPE.READ.FEATURES.ATTACHMENT]), loginRequired, validator.retrieveAttachments, apiV3FormValidator, async(req, res) => {
-
-    const limit = req.query.limit || await crowi.configManager.getConfig('customize:showPageLimitationS') || 10;
-    const pageNumber = req.query.pageNumber || 1;
-    const offset = (pageNumber - 1) * limit;
-
-    try {
-      const pageId = req.query.pageId;
-      // check whether accessible
-      const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
-      if (!isAccessible) {
-        const msg = 'Current user is not accessible to this page.';
-        return res.apiv3Err(new ErrorV3(msg, 'attachment-list-failed'), 403);
-      }
-
-      // directly get paging-size from db. not to delivery from client side.
+  router.get('/list', accessTokenParser([SCOPE.READ.FEATURES.ATTACHMENT]), loginRequired, validator.retrieveAttachments, apiV3FormValidator,
+    async(req, res) => {
 
-      const paginateResult = await Attachment.paginate(
-        { page: pageId },
-        {
-          limit,
-          offset,
-          populate: 'creator',
-        },
-      );
+      const limit = req.query.limit || await crowi.configManager.getConfig('customize:showPageLimitationS') || 10;
+      const pageNumber = req.query.pageNumber || 1;
+      const offset = (pageNumber - 1) * limit;
 
-      paginateResult.docs.forEach((doc) => {
-        if (doc.creator != null && doc.creator instanceof User) {
-          doc.creator = serializeUserSecurely(doc.creator);
+      try {
+        const pageId = req.query.pageId;
+        // check whether accessible
+        const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
+        if (!isAccessible) {
+          const msg = 'Current user is not accessible to this page.';
+          return res.apiv3Err(new ErrorV3(msg, 'attachment-list-failed'), 403);
         }
-      });
-
-      return res.apiv3({ paginateResult });
-    }
-    catch (err) {
-      logger.error('Attachment not found', err);
-      return res.apiv3Err(err, 500);
-    }
-  });
+
+        // directly get paging-size from db. not to delivery from client side.
+
+        const paginateResult = await Attachment.paginate(
+          { page: pageId },
+          {
+            limit,
+            offset,
+            populate: 'creator',
+          },
+        );
+
+        paginateResult.docs.forEach((doc) => {
+          if (doc.creator != null && doc.creator instanceof User) {
+            doc.creator = serializeUserSecurely(doc.creator);
+          }
+        });
+
+        return res.apiv3({ paginateResult });
+      }
+      catch (err) {
+        logger.error('Attachment not found', err);
+        return res.apiv3Err(err, 500);
+      }
+    });
 
 
   /**

+ 69 - 66
apps/app/src/server/routes/apiv3/in-app-notification.ts

@@ -25,91 +25,94 @@ module.exports = (crowi) => {
 
   const activityEvent = crowi.event('activity');
 
-  router.get('/list', accessTokenParser([SCOPE.READ.USER_SETTINGS.IN_APP_NOTIFICATION]), loginRequiredStrictly, async(req: CrowiRequest, res: ApiV3Response) => {
+  router.get('/list', accessTokenParser([SCOPE.READ.USER_SETTINGS.IN_APP_NOTIFICATION]), loginRequiredStrictly,
+    async(req: CrowiRequest, res: ApiV3Response) => {
     // user must be set by loginRequiredStrictly
     // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    const user = req.user!;
+      const user = req.user!;
 
-    const limit = req.query.limit != null
-      ? parseInt(req.query.limit.toString()) || 10
-      : 10;
+      const limit = req.query.limit != null
+        ? parseInt(req.query.limit.toString()) || 10
+        : 10;
+
+      let offset = 0;
+      if (req.query.offset != null) {
+        offset = parseInt(req.query.offset.toString(), 10);
+      }
 
-    let offset = 0;
-    if (req.query.offset != null) {
-      offset = parseInt(req.query.offset.toString(), 10);
-    }
+      const queryOptions = {
+        offset,
+        limit,
+      };
 
-    const queryOptions = {
-      offset,
-      limit,
-    };
+      // set in-app-notification status to categorize
+      if (req.query.status != null) {
+        Object.assign(queryOptions, { status: req.query.status });
+      }
 
-    // set in-app-notification status to categorize
-    if (req.query.status != null) {
-      Object.assign(queryOptions, { status: req.query.status });
-    }
+      const paginationResult = await inAppNotificationService.getLatestNotificationsByUser(user._id, queryOptions);
 
-    const paginationResult = await inAppNotificationService.getLatestNotificationsByUser(user._id, queryOptions);
 
+      const getActionUsersFromActivities = function(activities) {
+        return activities.map(({ user }) => user).filter((user, i, self) => self.indexOf(user) === i);
+      };
 
-    const getActionUsersFromActivities = function(activities) {
-      return activities.map(({ user }) => user).filter((user, i, self) => self.indexOf(user) === i);
-    };
+      const serializedDocs: Array<IInAppNotification> = paginationResult.docs.map((doc) => {
+        if (doc.user != null && doc.user instanceof User) {
+          doc.user = serializeUserSecurely(doc.user);
+        }
+        // To add a new property into mongoose doc, need to change the format of doc to an object
+        const docObj: IInAppNotification = doc.toObject();
+        const actionUsersNew = getActionUsersFromActivities(doc.activities);
 
-    const serializedDocs: Array<IInAppNotification> = paginationResult.docs.map((doc) => {
-      if (doc.user != null && doc.user instanceof User) {
-        doc.user = serializeUserSecurely(doc.user);
-      }
-      // To add a new property into mongoose doc, need to change the format of doc to an object
-      const docObj: IInAppNotification = doc.toObject();
-      const actionUsersNew = getActionUsersFromActivities(doc.activities);
+        const serializedActionUsers = actionUsersNew.map((actionUser) => {
+          return serializeUserSecurely(actionUser);
+        });
 
-      const serializedActionUsers = actionUsersNew.map((actionUser) => {
-        return serializeUserSecurely(actionUser);
+        docObj.actionUsers = serializedActionUsers;
+        return docObj;
       });
 
-      docObj.actionUsers = serializedActionUsers;
-      return docObj;
-    });
-
-    const serializedPaginationResult = {
-      ...paginationResult,
-      docs: serializedDocs,
-    };
+      const serializedPaginationResult = {
+        ...paginationResult,
+        docs: serializedDocs,
+      };
 
-    return res.apiv3(serializedPaginationResult);
-  });
+      return res.apiv3(serializedPaginationResult);
+    });
 
-  router.get('/status', accessTokenParser([SCOPE.READ.USER_SETTINGS.IN_APP_NOTIFICATION]), loginRequiredStrictly, async(req: CrowiRequest, res: ApiV3Response) => {
+  router.get('/status', accessTokenParser([SCOPE.READ.USER_SETTINGS.IN_APP_NOTIFICATION]), loginRequiredStrictly,
+    async(req: CrowiRequest, res: ApiV3Response) => {
     // user must be set by loginRequiredStrictly
     // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    const user = req.user!;
-
-    try {
-      const count = await inAppNotificationService.getUnreadCountByUser(user._id);
-      return res.apiv3({ count });
-    }
-    catch (err) {
-      return res.apiv3Err(err);
-    }
-  });
-
-  router.post('/open', accessTokenParser([SCOPE.WRITE.USER_SETTINGS.IN_APP_NOTIFICATION]), loginRequiredStrictly, async(req: CrowiRequest, res: ApiV3Response) => {
+      const user = req.user!;
+
+      try {
+        const count = await inAppNotificationService.getUnreadCountByUser(user._id);
+        return res.apiv3({ count });
+      }
+      catch (err) {
+        return res.apiv3Err(err);
+      }
+    });
+
+  router.post('/open', accessTokenParser([SCOPE.WRITE.USER_SETTINGS.IN_APP_NOTIFICATION]), loginRequiredStrictly,
+    async(req: CrowiRequest, res: ApiV3Response) => {
     // user must be set by loginRequiredStrictly
     // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    const user = req.user!;
-
-    const id = req.body.id;
-
-    try {
-      const notification = await inAppNotificationService.open(user, id);
-      const result = { notification };
-      return res.apiv3(result);
-    }
-    catch (err) {
-      return res.apiv3Err(err);
-    }
-  });
+      const user = req.user!;
+
+      const id = req.body.id;
+
+      try {
+        const notification = await inAppNotificationService.open(user, id);
+        const result = { notification };
+        return res.apiv3(result);
+      }
+      catch (err) {
+        return res.apiv3Err(err);
+      }
+    });
 
   router.put('/all-statuses-open', accessTokenParser([SCOPE.WRITE.USER_SETTINGS.IN_APP_NOTIFICATION]), loginRequiredStrictly, addActivity,
     async(req: CrowiRequest, res: ApiV3Response) => {

+ 28 - 26
apps/app/src/server/routes/apiv3/personal-setting/index.js

@@ -238,36 +238,37 @@ module.exports = (crowi) => {
    *                      type: object
    *                      description: personal params
    */
-  router.put('/', accessTokenParser([SCOPE.WRITE.USER_SETTINGS.INFO]), loginRequiredStrictly, addActivity, validator.personal, apiV3FormValidator, async(req, res) => {
+  router.put('/', accessTokenParser([SCOPE.WRITE.USER_SETTINGS.INFO]), loginRequiredStrictly, addActivity, validator.personal, apiV3FormValidator,
+    async(req, res) => {
 
-    try {
-      const user = await User.findOne({ _id: req.user.id });
-      user.name = req.body.name;
-      user.email = req.body.email;
-      user.lang = req.body.lang;
-      user.isEmailPublished = req.body.isEmailPublished;
-      user.slackMemberId = req.body.slackMemberId;
-
-      const isUniqueEmail = await user.isUniqueEmail();
-
-      if (!isUniqueEmail) {
-        logger.error('email-is-not-unique');
-        return res.apiv3Err(new ErrorV3('The email is already in use', 'email-is-already-in-use'));
-      }
+      try {
+        const user = await User.findOne({ _id: req.user.id });
+        user.name = req.body.name;
+        user.email = req.body.email;
+        user.lang = req.body.lang;
+        user.isEmailPublished = req.body.isEmailPublished;
+        user.slackMemberId = req.body.slackMemberId;
+
+        const isUniqueEmail = await user.isUniqueEmail();
+
+        if (!isUniqueEmail) {
+          logger.error('email-is-not-unique');
+          return res.apiv3Err(new ErrorV3('The email is already in use', 'email-is-already-in-use'));
+        }
 
-      const updatedUser = await user.save();
+        const updatedUser = await user.save();
 
-      const parameters = { action: SupportedAction.ACTION_USER_PERSONAL_SETTINGS_UPDATE };
-      activityEvent.emit('update', res.locals.activity._id, parameters);
+        const parameters = { action: SupportedAction.ACTION_USER_PERSONAL_SETTINGS_UPDATE };
+        activityEvent.emit('update', res.locals.activity._id, parameters);
 
-      return res.apiv3({ updatedUser });
-    }
-    catch (err) {
-      logger.error(err);
-      return res.apiv3Err('update-personal-settings-failed');
-    }
+        return res.apiv3({ updatedUser });
+      }
+      catch (err) {
+        logger.error(err);
+        return res.apiv3Err('update-personal-settings-failed');
+      }
 
-  });
+    });
 
   /**
    * @swagger
@@ -664,7 +665,8 @@ module.exports = (crowi) => {
    *                  type: object
    *                  description: editor settings
    */
-  router.put('/editor-settings', accessTokenParser([SCOPE.WRITE.USER_SETTINGS.OTHER]), loginRequiredStrictly, addActivity, validator.editorSettings, apiV3FormValidator,
+  router.put('/editor-settings', accessTokenParser([SCOPE.WRITE.USER_SETTINGS.OTHER]), loginRequiredStrictly,
+    addActivity, validator.editorSettings, apiV3FormValidator,
     async(req, res) => {
       const query = { userId: req.user.id };
       const { body } = req;