feat: merge changes

allow selecting main topic to merge into
allow specifying a new title for merge topic
upon merge go to correct topic
new tests for merging with options
This commit is contained in:
Barış Soner Uşaklı
2020-06-10 12:48:32 -04:00
parent 8591f5d2cc
commit bb3aa54006
4 changed files with 110 additions and 16 deletions

View File

@@ -4,14 +4,18 @@ const topics = require('../../topics');
const privileges = require('../../privileges');
module.exports = function (SocketTopics) {
SocketTopics.merge = async function (socket, tids) {
if (!Array.isArray(tids)) {
SocketTopics.merge = async function (socket, data) {
if (!data || !Array.isArray(data.tids)) {
throw new Error('[[error:invalid-data]]');
}
const allowed = await Promise.all(tids.map(tid => privileges.topics.isAdminOrMod(tid, socket.uid)));
const allowed = await Promise.all(data.tids.map(tid => privileges.topics.isAdminOrMod(tid, socket.uid)));
if (allowed.includes(false)) {
throw new Error('[[error:no-privileges]]');
}
await topics.merge(tids, socket.uid);
if (data.options && data.options.mainTid && !data.tids.includes(data.options.mainTid)) {
throw new Error('[[error:invalid-data]]');
}
const mergeIntoTid = await topics.merge(data.tids, socket.uid, data.options);
return mergeIntoTid;
};
};

View File

@@ -4,10 +4,18 @@ const async = require('async');
const plugins = require('../plugins');
module.exports = function (Topics) {
Topics.merge = async function (tids, uid) {
const mergeIntoTid = findOldestTopic(tids);
Topics.merge = async function (tids, uid, options) {
options = options || {};
const oldestTid = findOldestTopic(tids);
let mergeIntoTid = oldestTid;
if (options.mainTid) {
mergeIntoTid = options.mainTid;
} else if (options.newTopicTitle) {
mergeIntoTid = await createNewTopic(options.newTopicTitle, oldestTid);
}
const otherTids = tids.filter(tid => tid && parseInt(tid, 10) !== parseInt(mergeIntoTid, 10));
const otherTids = tids.sort((a, b) => a - b)
.filter(tid => tid && parseInt(tid, 10) !== parseInt(mergeIntoTid, 10));
await async.eachSeries(otherTids, async function (tid) {
const pids = await Topics.getPids(tid);
@@ -25,8 +33,19 @@ module.exports = function (Topics) {
});
plugins.fireHook('action:topic.merge', { uid: uid, tids: tids, mergeIntoTid: mergeIntoTid, otherTids: otherTids });
return mergeIntoTid;
};
async function createNewTopic(title, oldestTid) {
const topicData = await Topics.getTopicFields(oldestTid, ['uid', 'cid']);
const tid = await Topics.create({
uid: topicData.uid,
cid: topicData.cid,
title: title,
});
return tid;
}
function findOldestTopic(tids) {
return Math.min.apply(null, tids);
}