Files
NodeBB/src/posts/bookmarks.js

69 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-10-08 19:09:48 +03:00
'use strict';
2019-07-17 00:17:21 -04:00
const db = require('../database');
const plugins = require('../plugins');
2016-10-08 19:09:48 +03:00
module.exports = function (Posts) {
2019-07-17 00:17:21 -04:00
Posts.bookmark = async function (pid, uid) {
return await toggleBookmark('bookmark', pid, uid);
2016-10-08 19:09:48 +03:00
};
2019-07-17 00:17:21 -04:00
Posts.unbookmark = async function (pid, uid) {
return await toggleBookmark('unbookmark', pid, uid);
2016-10-08 19:09:48 +03:00
};
2019-07-17 00:17:21 -04:00
async function toggleBookmark(type, pid, uid) {
2018-11-12 00:20:44 -05:00
if (parseInt(uid, 10) <= 0) {
2019-07-17 00:17:21 -04:00
throw new Error('[[error:not-logged-in]]');
2016-10-08 19:09:48 +03:00
}
2019-07-17 00:17:21 -04:00
const isBookmarking = type === 'bookmark';
2016-10-08 19:09:48 +03:00
2019-07-17 00:17:21 -04:00
const [postData, hasBookmarked] = await Promise.all([
Posts.getPostFields(pid, ['pid', 'uid']),
Posts.hasBookmarked(pid, uid),
]);
2016-10-08 19:09:48 +03:00
2019-07-17 00:17:21 -04:00
if (isBookmarking && hasBookmarked) {
throw new Error('[[error:already-bookmarked]]');
}
2016-10-08 19:09:48 +03:00
2019-07-17 00:17:21 -04:00
if (!isBookmarking && !hasBookmarked) {
throw new Error('[[error:already-unbookmarked]]');
}
2016-10-08 19:09:48 +03:00
2019-07-17 00:17:21 -04:00
if (isBookmarking) {
2021-02-03 23:59:08 -07:00
await db.sortedSetAdd(`uid:${uid}:bookmarks`, Date.now(), pid);
2019-07-17 00:17:21 -04:00
} else {
2021-02-03 23:59:08 -07:00
await db.sortedSetRemove(`uid:${uid}:bookmarks`, pid);
2019-07-17 00:17:21 -04:00
}
2021-02-03 23:59:08 -07:00
await db[isBookmarking ? 'setAdd' : 'setRemove'](`pid:${pid}:users_bookmarked`, uid);
postData.bookmarks = await db.setCount(`pid:${pid}:users_bookmarked`);
2019-07-17 00:17:21 -04:00
await Posts.setPostField(pid, 'bookmarks', postData.bookmarks);
2021-02-03 23:59:08 -07:00
plugins.hooks.fire(`action:post.${type}`, {
2019-07-17 00:17:21 -04:00
pid: pid,
uid: uid,
owner: postData.uid,
current: hasBookmarked ? 'bookmarked' : 'unbookmarked',
});
2016-10-08 19:09:48 +03:00
2019-07-17 00:17:21 -04:00
return {
post: postData,
isBookmarked: isBookmarking,
};
2016-10-08 19:09:48 +03:00
}
2019-07-17 00:17:21 -04:00
Posts.hasBookmarked = async function (pid, uid) {
2018-11-12 00:20:44 -05:00
if (parseInt(uid, 10) <= 0) {
2019-07-17 00:17:21 -04:00
return Array.isArray(pid) ? pid.map(() => false) : false;
2016-10-08 19:09:48 +03:00
}
if (Array.isArray(pid)) {
2021-02-03 23:59:08 -07:00
const sets = pid.map(pid => `pid:${pid}:users_bookmarked`);
2019-07-17 00:17:21 -04:00
return await db.isMemberOfSets(sets, uid);
2016-10-08 19:09:48 +03:00
}
2021-02-03 23:59:08 -07:00
return await db.isSetMember(`pid:${pid}:users_bookmarked`, uid);
2016-10-08 19:09:48 +03:00
};
};