2017-03-25 08:43:55 +01:00
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
import $ from 'cafy';
|
|
|
|
import Vote from '../../../models/poll-vote';
|
2018-02-02 02:31:17 +01:00
|
|
|
import Post, { pack } from '../../../models/post';
|
2017-03-25 08:43:55 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Get recommended polls
|
|
|
|
*
|
|
|
|
* @param {any} params
|
|
|
|
* @param {any} user
|
|
|
|
* @return {Promise<any>}
|
|
|
|
*/
|
|
|
|
module.exports = (params, user) => new Promise(async (res, rej) => {
|
|
|
|
// Get 'limit' parameter
|
|
|
|
const [limit = 10, limitErr] = $(params.limit).optional.number().range(1, 100).$;
|
|
|
|
if (limitErr) return rej('invalid limit param');
|
|
|
|
|
|
|
|
// Get 'offset' parameter
|
|
|
|
const [offset = 0, offsetErr] = $(params.offset).optional.number().min(0).$;
|
|
|
|
if (offsetErr) return rej('invalid offset param');
|
|
|
|
|
|
|
|
// Get votes
|
|
|
|
const votes = await Vote.find({
|
2018-03-29 07:48:47 +02:00
|
|
|
userId: user._id
|
2017-03-25 08:43:55 +01:00
|
|
|
}, {
|
|
|
|
fields: {
|
|
|
|
_id: false,
|
2018-03-29 07:48:47 +02:00
|
|
|
postId: true
|
2017-03-25 08:43:55 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2018-03-29 07:48:47 +02:00
|
|
|
const nin = votes && votes.length != 0 ? votes.map(v => v.postId) : [];
|
2017-03-25 08:43:55 +01:00
|
|
|
|
|
|
|
const posts = await Post
|
|
|
|
.find({
|
|
|
|
_id: {
|
|
|
|
$nin: nin
|
|
|
|
},
|
2018-03-29 07:48:47 +02:00
|
|
|
userId: {
|
2017-03-25 08:50:21 +01:00
|
|
|
$ne: user._id
|
|
|
|
},
|
2017-03-25 08:43:55 +01:00
|
|
|
poll: {
|
|
|
|
$exists: true,
|
|
|
|
$ne: null
|
|
|
|
}
|
|
|
|
}, {
|
|
|
|
limit: limit,
|
|
|
|
skip: offset,
|
|
|
|
sort: {
|
|
|
|
_id: -1
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// Serialize
|
|
|
|
res(await Promise.all(posts.map(async post =>
|
2018-02-02 00:21:30 +01:00
|
|
|
await pack(post, user, { detail: true }))));
|
2017-03-25 08:43:55 +01:00
|
|
|
});
|