Optimize notification endpoint
authorChocobozzz <me@florianbigard.com>
Thu, 9 Jan 2020 08:01:08 +0000 (09:01 +0100)
committerChocobozzz <me@florianbigard.com>
Thu, 9 Jan 2020 08:27:18 +0000 (09:27 +0100)
server/models/account/user-notification.ts

index ccb81b891f68f77a141a314335addc3e3b60fe59..a05f30175cc7b21f9e12ce41d7f0973d3127c024 100644 (file)
@@ -337,25 +337,25 @@ export class UserNotificationModel extends Model<UserNotificationModel> {
   ActorFollow: ActorFollowModel
 
   static listForApi (userId: number, start: number, count: number, sort: string, unread?: boolean) {
+    const where = { userId }
+
     const query: FindOptions = {
       offset: start,
       limit: count,
       order: getSort(sort),
-      where: {
-        userId
-      }
+      where
     }
 
     if (unread !== undefined) query.where['read'] = !unread
 
-    return UserNotificationModel.scope(ScopeNames.WITH_ALL)
-                                .findAndCountAll(query)
-                                .then(({ rows, count }) => {
-                                  return {
-                                    data: rows,
-                                    total: count
-                                  }
-                                })
+    return Promise.all([
+      UserNotificationModel.count({ where })
+        .then(count => count || 0),
+
+      count === 0
+        ? []
+        : UserNotificationModel.scope(ScopeNames.WITH_ALL).findAll(query)
+    ]).then(([ total, data ]) => ({ total, data }))
   }
 
   static markAsRead (userId: number, notificationIds: number[]) {