From 9b8c834ef00b70cc4edeaf3c9023c1aac41b30d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bar=C4=B1=C5=9F=20Soner=20U=C5=9Fakl=C4=B1?= Date: Thu, 11 Jul 2024 22:24:32 -0400 Subject: [PATCH] perf: get rid of exists call, load all attachments in one call --- src/posts/attachments.js | 17 ++++++++++++++--- src/topics/thumbs.js | 19 +++++++++---------- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/posts/attachments.js b/src/posts/attachments.js index 75532f5fc8..313eb47019 100644 --- a/src/posts/attachments.js +++ b/src/posts/attachments.js @@ -8,9 +8,20 @@ const db = require('../database'); const Attachments = module.exports; const posts = require('./index'); -Attachments.get = async (pid) => { - const hashes = await posts.getPostField(pid, `attachments`); - return Attachments.getAttachments(hashes); +Attachments.get = async (pids) => { + const isArray = Array.isArray(pids); + if (!isArray) { + pids = [pids]; + } + const postData = await posts.getPostsFields(pids, [`attachments`]); + const allHashes = _.flatten(postData.map(p => p && p.attachments)); + const allAttachments = await Attachments.getAttachments(allHashes); + const hashToAttachment = _.zipObject(allHashes, allAttachments); + const data = postData.map((post, idx) => { + const pidHashes = post ? post.attachments : []; + return pidHashes.map(hash => hashToAttachment[hash]); + }); + return isArray ? data : data[0]; }; Attachments.getAttachments = async (hashes) => { diff --git a/src/topics/thumbs.js b/src/topics/thumbs.js index 4e770a043a..9fd62eb0e4 100644 --- a/src/topics/thumbs.js +++ b/src/topics/thumbs.js @@ -50,22 +50,21 @@ Thumbs.get = async function (tids) { const hasTimestampPrefix = /^\d+-/; const upload_url = nconf.get('relative_path') + nconf.get('upload_url'); - const exists = await topics.exists(tids); const sets = tids.map(tid => `${validator.isUUID(String(tid)) ? 'draft' : 'topic'}:${tid}:thumbs`); const thumbs = await Promise.all(sets.map(getThumbs)); // Add attachments to thumb sets - await Promise.all(tids.map(async (tid, idx) => { - if (exists[idx]) { - const mainPid = await topics.getTopicField(tid, 'mainPid'); - let attachments = await posts.attachments.get(mainPid); - attachments = attachments.filter(attachment => attachment.mediaType.startsWith('image/')); + const mainPids = await topics.getTopicsFields(tids, ['mainPid']); + const mainPidAttachments = await posts.attachments.get(mainPids); + mainPidAttachments.forEach((attachments, idx) => { + attachments = attachments.filter( + attachment => attachment.mediaType.startsWith('image/') + ); - if (attachments.length) { - thumbs[idx].push(...attachments.map(attachment => attachment.url)); - } + if (attachments.length) { + thumbs[idx].push(...attachments.map(attachment => attachment.url)); } - })); + }); let response = thumbs.map((thumbSet, idx) => thumbSet.map(thumb => ({ id: tids[idx],