refactor: assertTopic to only call setObject when it is a new topic

This commit is contained in:
Julian Lam
2024-02-28 13:29:21 -05:00
parent 96a3a7465f
commit bdcd862c1b

View File

@@ -205,6 +205,8 @@ Notes.assertTopic = async (uid, id) => {
} }
let { pid: mainPid, tid, uid: authorId, timestamp, name, content } = chain[chain.length - 1]; let { pid: mainPid, tid, uid: authorId, timestamp, name, content } = chain[chain.length - 1];
const hasTid = !!tid;
const members = await db.isSortedSetMembers(`tid:${tid}:posts`, chain.map(p => p.pid)); const members = await db.isSortedSetMembers(`tid:${tid}:posts`, chain.map(p => p.pid));
if (tid && members.every(Boolean)) { if (tid && members.every(Boolean)) {
// All cached, return early. // All cached, return early.
@@ -212,7 +214,18 @@ Notes.assertTopic = async (uid, id) => {
return tid; return tid;
} }
const cid = tid ? await topics.getTopicField(tid, 'cid') : -1; let cid;
let title;
if (hasTid) {
({ cid, title, mainPid } = await topics.getTopicFields(tid, ['cid', 'title', 'mainPid']));
} else {
// mainPid ok to leave as-is
cid = -1;
title = name || utils.decodeHTMLEntities(utils.stripHTMLTags(content));
if (title.length > meta.config.maximumTitleLength) {
title = `${title.slice(0, meta.config.maximumTitleLength)}...`;
}
}
// Privilege check for local categories // Privilege check for local categories
const privilege = `topics:${tid ? 'reply' : 'create'}`; const privilege = `topics:${tid ? 'reply' : 'create'}`;
@@ -221,11 +234,6 @@ Notes.assertTopic = async (uid, id) => {
return null; return null;
} }
let title = tid ? await topics.getTopicField(tid, 'title') : name || utils.decodeHTMLEntities(utils.stripHTMLTags(content));
if (title.length > meta.config.maximumTitleLength) {
title = `${title.slice(0, meta.config.maximumTitleLength)}...`;
}
tid = tid || utils.generateUUID(); tid = tid || utils.generateUUID();
const unprocessed = chain.filter((p, idx) => !members[idx]); const unprocessed = chain.filter((p, idx) => !members[idx]);
@@ -237,11 +245,14 @@ Notes.assertTopic = async (uid, id) => {
]; ];
// mainPid doesn't belong in posts zset // mainPid doesn't belong in posts zset
ids.pop(); if (ids.includes(mainPid)) {
timestamps.pop(); const idx = ids.indexOf(mainPid);
ids.splice(idx, 1);
timestamps.splice(idx, 1);
}
await Promise.all([ await Promise.all([
db.setObject(`topic:${tid}`, { !hasTid ? db.setObject(`topic:${tid}`, {
tid, tid,
uid: authorId, uid: authorId,
cid: cid, cid: cid,
@@ -249,7 +260,7 @@ Notes.assertTopic = async (uid, id) => {
title, title,
slug: `${tid}/${slugify(title)}`, slug: `${tid}/${slugify(title)}`,
timestamp, timestamp,
}), }) : null,
db.sortedSetAdd(`tid:${tid}:posts`, timestamps, ids), db.sortedSetAdd(`tid:${tid}:posts`, timestamps, ids),
Notes.assert(uid, unprocessed), Notes.assert(uid, unprocessed),
]); ]);