Node.js based forum software built for the modern web
perf: get rid of exists call, load all attachments in one call
Barış Soner Uşaklı9b8c834ef00b
diff --git a/src/posts/attachments.js b/src/posts/attachments.jsindex 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.jsindex 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/'));-- if (attachments.length) {- thumbs[idx].push(...attachments.map(attachment => attachment.url));- }+ 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));}- }));+ });let response = thumbs.map((thumbSet, idx) => thumbSet.map(thumb => ({id: tids[idx],