Files
NodeBB/src/posts/data.js

73 lines
2.1 KiB
JavaScript
Raw Normal View History

2018-10-17 15:24:17 -04:00
'use strict';
2019-07-17 00:17:21 -04:00
const db = require('../database');
const plugins = require('../plugins');
const utils = require('../utils');
2018-10-17 15:24:17 -04:00
2018-10-21 19:33:46 -04:00
const intFields = [
'uid', 'pid', 'tid', 'deleted', 'timestamp',
'upvotes', 'downvotes', 'deleterUid', 'edited',
'replies',
2018-10-21 19:33:46 -04:00
];
2018-10-20 16:31:16 -04:00
2018-10-17 15:24:17 -04:00
module.exports = function (Posts) {
2019-07-17 00:17:21 -04:00
Posts.getPostsFields = async function (pids, fields) {
2018-10-20 16:31:16 -04:00
if (!Array.isArray(pids) || !pids.length) {
2019-07-17 00:17:21 -04:00
return [];
2018-10-20 16:31:16 -04:00
}
2019-07-17 00:17:21 -04:00
const keys = pids.map(pid => 'post:' + pid);
2020-06-19 12:03:33 -04:00
const postData = await (fields.length ? db.getObjectsFields(keys, fields) : db.getObjects(keys));
const result = await plugins.fireHook('filter:post.getFields', {
pids: pids,
posts: postData,
fields: fields,
});
2019-07-17 00:17:21 -04:00
result.posts.forEach(post => modifyPost(post, fields));
return Array.isArray(result.posts) ? result.posts : null;
2018-10-17 15:24:17 -04:00
};
2019-07-17 00:17:21 -04:00
Posts.getPostData = async function (pid) {
const posts = await Posts.getPostsFields([pid], []);
return posts && posts.length ? posts[0] : null;
2018-10-20 16:31:16 -04:00
};
2019-07-17 00:17:21 -04:00
Posts.getPostsData = async function (pids) {
return await Posts.getPostsFields(pids, []);
2018-10-17 15:24:17 -04:00
};
2019-07-17 00:17:21 -04:00
Posts.getPostField = async function (pid, field) {
const post = await Posts.getPostFields(pid, [field]);
return post ? post[field] : null;
2018-10-17 15:24:17 -04:00
};
2019-07-17 00:17:21 -04:00
Posts.getPostFields = async function (pid, fields) {
const posts = await Posts.getPostsFields([pid], fields);
return posts ? posts[0] : null;
2018-10-17 15:24:17 -04:00
};
2019-07-17 00:17:21 -04:00
Posts.setPostField = async function (pid, field, value) {
await Posts.setPostFields(pid, { [field]: value });
2018-10-17 15:24:17 -04:00
};
2019-07-17 00:17:21 -04:00
Posts.setPostFields = async function (pid, data) {
await db.setObject('post:' + pid, data);
data.pid = pid;
plugins.fireHook('action:post.setFields', { data: data });
2018-10-17 15:24:17 -04:00
};
};
2018-10-20 16:31:16 -04:00
2018-10-25 19:58:01 -04:00
function modifyPost(post, fields) {
2018-10-20 16:31:16 -04:00
if (post) {
2018-10-25 19:58:01 -04:00
db.parseIntFields(post, intFields, fields);
2018-10-21 19:33:46 -04:00
if (post.hasOwnProperty('upvotes') && post.hasOwnProperty('downvotes')) {
post.votes = post.upvotes - post.downvotes;
}
if (post.hasOwnProperty('timestamp')) {
post.timestampISO = utils.toISOString(post.timestamp);
}
if (post.hasOwnProperty('edited')) {
post.editedISO = post.edited !== 0 ? utils.toISOString(post.edited) : '';
}
2018-10-20 16:31:16 -04:00
}
}