Skip to content

Node.js based forum software built for the modern web

refactor: get rid of exists db call, use promise.parallel

Barış Soner Uşaklı8895b152c2c5
diff --git a/src/posts/create.js b/src/posts/create.js
index ae9ebdbc85..b248f04a36 100644
--- a/src/posts/create.js
+++ b/src/posts/create.js
@@ -10,7 +10,6 @@ const topics = require('../topics');
const categories = require('../categories');
const groups = require('../groups');
const privileges = require('../privileges');
-const utils = require('../utils');
module.exports = function (Posts) {
Posts.create = async function (data) {
@@ -26,16 +25,7 @@ module.exports = function (Posts) {
}
if (data.toPid) {
- const toPidExists = await Posts.exists(data.toPid);
- const toPidDeleted = await Posts.getPostField(data.toPid, 'deleted');
- const canViewToPid = await privileges.posts.can('posts:view_deleted', data.toPid, uid);
-
- if (
- !utils.isNumber(data.toPid) || !toPidExists ||
- (toPidDeleted && !canViewToPid)
- ) {
- throw new Error('[[error:invalid-pid]]');
- }
+ await checkToPid(data.toPid);
}
const pid = await db.incrObjectField('global', 'nextPid');
@@ -90,4 +80,15 @@ module.exports = function (Posts) {
db.incrObjectField(`post:${postData.toPid}`, 'replies'),
]);
}
+
+ async function checkToPid(toPid, uid) {
+ const [toPost, canViewToPid] = await Promise.all([
+ Posts.getPostFields(toPid, ['pid', 'deleted']),
+ privileges.posts.can('posts:view_deleted', toPid, uid),
+ ]);
+ const toPidExists = !!toPost.pid;
+ if (!toPidExists || (toPost.deleted && !canViewToPid)) {
+ throw new Error('[[error:invalid-pid]]');
+ }
+ }
};