From 1d7e0c634171fae83f0436328beb3ae742026844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bar=C4=B1=C5=9F=20Soner=20U=C5=9Fakl=C4=B1?= Date: Thu, 22 Aug 2019 13:04:14 -0400 Subject: [PATCH] feat: allow floating pinned topics to top in getSortedTopics --- src/controllers/recent.js | 1 + src/topics/sorted.js | 31 +++++++++++++++++++++++-------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/controllers/recent.js b/src/controllers/recent.js index 2e24641bee..7df255de4a 100644 --- a/src/controllers/recent.js +++ b/src/controllers/recent.js @@ -55,6 +55,7 @@ recentController.getData = async function (req, url, sort) { filter: filter, term: term, sort: sort, + floatPinned: req.query.pinned, query: req.query, }); diff --git a/src/topics/sorted.js b/src/topics/sorted.js index 463ac72d5f..57903be8f5 100644 --- a/src/topics/sorted.js +++ b/src/topics/sorted.js @@ -42,7 +42,7 @@ module.exports = function (Topics) { } else { tids = await Topics.getLatestTidsFromSet('topics:tid', 0, -1, params.term); } - if (params.term !== 'alltime' || (params.cids && params.sort !== 'recent')) { + if (params.term !== 'alltime' || params.cids || params.floatPinned) { tids = await sortTids(tids, params); } return await filterTids(tids, params); @@ -53,10 +53,10 @@ module.exports = function (Topics) { const pinnedSets = []; cids.forEach(function (cid) { if (sort === 'recent') { - sets.push('cid:' + cid + ':tids:lastposttime'); - return; + sets.push('cid:' + cid + ':tids'); + } else { + sets.push('cid:' + cid + ':tids' + (sort ? ':' + sort : '')); } - sets.push('cid:' + cid + ':tids' + (sort ? ':' + sort : '')); pinnedSets.push('cid:' + cid + ':tids:pinned'); }); const [tids, pinnedTids] = await Promise.all([ @@ -67,15 +67,30 @@ module.exports = function (Topics) { } async function sortTids(tids, params) { - const topicData = await Topics.getTopicsFields(tids, ['tid', 'lastposttime', 'upvotes', 'downvotes', 'postcount']); - var sortFn = sortRecent; + const topicData = await Topics.getTopicsFields(tids, ['tid', 'lastposttime', 'upvotes', 'downvotes', 'postcount', 'pinned']); + let sortFn = sortRecent; if (params.sort === 'posts') { sortFn = sortPopular; } else if (params.sort === 'votes') { sortFn = sortVotes; } - tids = topicData.sort(sortFn).map(topic => topic && topic.tid); - return tids; + + if (params.floatPinned) { + floatPinned(topicData, sortFn); + } else { + topicData.sort(sortFn); + } + + return topicData.map(topic => topic && topic.tid); + } + + function floatPinned(topicData, sortFn) { + topicData.sort((a, b) => { + if (a.pinned !== b.pinned) { + return b.pinned - a.pinned; + } + return sortFn(a, b); + }); } function sortRecent(a, b) {