From d7d73179eedf8110d51c9a8a163a341b930fdb63 Mon Sep 17 00:00:00 2001 From: Louis Laureys Date: Sun, 12 Sep 2021 22:15:39 +0200 Subject: [PATCH] Make thread counters work correctly --- lib/api/messages.js | 53 +++++++++++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/lib/api/messages.js b/lib/api/messages.js index 13e107a..2869e4a 100644 --- a/lib/api/messages.js +++ b/lib/api/messages.js @@ -61,6 +61,35 @@ module.exports = (db, server, messageHandler, userHandler, storageHandler, setti }); }); + const addThreadCountersToMessageList = async (user, list) => { + const threadIdsToCount = list.map(message => message.thread); + const threadCounts = await db.database + .collection('messages') + .aggregate([ + { + $match: { + user: new ObjectId(user), + thread: { $in: threadIdsToCount } + } + }, + { + $group: { + _id: '$thread', + count: { + $sum: 1 + } + } + } + ]) + .toArray(); + + return list.map(message => { + const matchingThreadCount = threadCounts.find(thread => thread._id.toString() === message.thread.toString()); + message.threadMessageCount = matchingThreadCount ? matchingThreadCount.count : undefined + return message + }); + }; + const putMessageHandler = async (req, res, next) => { res.charSet('utf-8'); @@ -413,16 +442,7 @@ module.exports = (db, server, messageHandler, userHandler, storageHandler, setti } if (threadCounters) { - const threadIdsToFetch = listing.results.map(message => message.thread); - const threads = await db.database - .collection('threads') - .find({ _id: { $in: threadIdsToFetch } }) - .toArray(); - - listing.results = listing.results.map(message => ({ - ...message, - threadEntity: threads.find(thread => thread._id.toString() === message.thread.toString()) - })); + listing.results = await addThreadCountersToMessageList(user, listing.results); } let response = { @@ -837,16 +857,7 @@ module.exports = (db, server, messageHandler, userHandler, storageHandler, setti } if (threadCounters) { - const threadIdsToFetch = listing.results.map(message => message.thread); - const threads = await db.database - .collection('threads') - .find({ _id: { $in: threadIdsToFetch } }) - .toArray(); - - listing.results = listing.results.map(message => ({ - ...message, - threadEntity: threads.find(thread => thread._id.toString() === message.thread.toString()) - })); + listing.results = await addThreadCountersToMessageList(user, listing.results); } let response = { @@ -3169,7 +3180,7 @@ function formatMessageListing(messageData) { id: messageData.uid, mailbox: messageData.mailbox, thread: messageData.thread, - threadMessageCount: messageData.threadEntity?.ids?.length, + threadMessageCount: messageData.threadMessageCount, from: from && from[0], to, cc,