refactor: posts api

This commit is contained in:
Barış Soner Uşaklı
2020-10-17 22:59:12 -04:00
parent 272e73da53
commit d9a16855d0
9 changed files with 104 additions and 123 deletions

View File

@@ -3,8 +3,11 @@
const url = require('url');
const user = require('../user');
const topics = require('../topics');
const posts = require('../posts');
const privileges = require('../privileges');
const plugins = require('../plugins');
const socketHelpers = require('../socket.io/helpers');
const websockets = require('../socket.io');
const events = require('../events');
// creates a slimmed down version of the request object
@@ -34,7 +37,6 @@ exports.buildReqObject = (req, payload) => {
};
};
exports.doTopicAction = async function (action, event, caller, { tids }) {
if (!Array.isArray(tids)) {
throw new Error('[[error:invalid-tid]]');
@@ -73,3 +75,59 @@ async function logTopicAction(action, req, tid, title) {
title: String(title),
});
}
exports.postCommand = async function (caller, command, eventName, notification, data) {
if (!caller.uid) {
throw new Error('[[error:not-logged-in]]');
}
if (!data || !data.pid) {
throw new Error('[[error:invalid-data]]');
}
if (!data.room_id) {
throw new Error('[[error:invalid-room-id, ' + data.room_id + ' ]]');
}
const [exists, deleted] = await Promise.all([
posts.exists(data.pid),
posts.getPostField(data.pid, 'deleted'),
]);
if (!exists) {
throw new Error('[[error:invalid-pid]]');
}
if (deleted) {
throw new Error('[[error:post-deleted]]');
}
/*
hooks:
filter:post.upvote
filter:post.downvote
filter:post.unvote
filter:post.bookmark
filter:post.unbookmark
*/
const filteredData = await plugins.fireHook('filter:post.' + command, {
data: data,
uid: caller.uid,
});
return await executeCommand(caller, command, eventName, notification, filteredData.data);
};
async function executeCommand(caller, command, eventName, notification, data) {
const result = await posts[command](data.pid, caller.uid);
if (result && eventName) {
websockets.in('uid_' + caller.uid).emit('posts.' + command, result);
websockets.in(data.room_id).emit('event:' + eventName, result);
}
if (result && command === 'upvote') {
socketHelpers.upvote(result, notification);
} else if (result && notification) {
socketHelpers.sendNotificationToPostOwner(data.pid, caller.uid, command, notification);
} else if (result && command === 'unvote') {
socketHelpers.rescindUpvoteNotification(data.pid, caller.uid);
}
return result;
}