Skip to content

Node.js based forum software built for the modern web

refactor: change incrementViewCount and markAsRead to async/await

Barış Soner Uşaklı2c35d0ba8763
diff --git a/src/controllers/topics.js b/src/controllers/topics.js
index ad3b219ee4..e777aded8a 100644
--- a/src/controllers/topics.js
+++ b/src/controllers/topics.js
@@ -1,7 +1,6 @@
'use strict';
const nconf = require('nconf');
-const winston = require('winston');
const user = require('../user');
const meta = require('../meta');
@@ -90,6 +89,9 @@ topicsController.get = async function getTopic(req, res, callback) {
await Promise.all([
buildBreadcrumbs(topicData),
addTags(topicData, req, res),
+ incrementViewCount(req, tid),
+ markAsRead(req, tid),
+ analytics.increment(['pageviews:byCid:' + topicData.category.cid]),
]);
topicData.pagination = pagination.create(currentPage, pageCount, req.query);
@@ -98,12 +100,6 @@ topicsController.get = async function getTopic(req, res, callback) {
res.locals.linkTags.push(rel);
});
- incrementViewCount(req, tid);
-
- markAsRead(req, tid);
-
- analytics.increment(['pageviews:byCid:' + topicData.category.cid]);
-
res.render('topic', topicData);
};
@@ -126,27 +122,24 @@ function calculateStartStop(page, postIndex, settings) {
return { start: Math.max(0, start), stop: Math.max(0, stop) };
}
-function incrementViewCount(req, tid) {
+async function incrementViewCount(req, tid) {
if (req.uid >= 1) {
req.session.tids_viewed = req.session.tids_viewed || {};
if (!req.session.tids_viewed[tid] || req.session.tids_viewed[tid] < Date.now() - 3600000) {
- topics.increaseViewCount(tid);
+ await topics.increaseViewCount(tid);
req.session.tids_viewed[tid] = Date.now();
}
}
}
-function markAsRead(req, tid) {
+async function markAsRead(req, tid) {
if (req.loggedIn) {
- topics.markAsRead([tid], req.uid, function (err, markedRead) {
- if (err) {
- return winston.error(err.stack);
- }
- if (markedRead) {
- topics.pushUnreadCount(req.uid);
- topics.markTopicNotificationsRead([tid], req.uid);
- }
- });
+ const markedRead = await topics.markAsRead([tid], req.uid);
+ const promises = [topics.markTopicNotificationsRead([tid], req.uid)];
+ if (markedRead) {
+ promises.push(topics.pushUnreadCount(req.uid));
+ }
+ await Promise.all(promises);
}
}
diff --git a/src/socket.io/topics/unread.js b/src/socket.io/topics/unread.js
index 0d8021a398..d7662884af 100644
--- a/src/socket.io/topics/unread.js
+++ b/src/socket.io/topics/unread.js
@@ -10,11 +10,11 @@ module.exports = function (SocketTopics) {
throw new Error('[[error:invalid-data]]');
}
const hasMarked = await topics.markAsRead(tids, socket.uid);
+ const promises = [topics.markTopicNotificationsRead(tids, socket.uid)];
if (hasMarked) {
- topics.pushUnreadCount(socket.uid);
-
- topics.markTopicNotificationsRead(tids, socket.uid);
+ promises.push(topics.pushUnreadCount(socket.uid));
}
+ await Promise.all(promises);
};
SocketTopics.markTopicNotificationsRead = async function (socket, tids) {