2016-12-28 23:49:51 +01:00
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
2017-03-03 11:52:36 +01:00
|
|
|
import it from '../../../it';
|
2016-12-28 23:49:51 +01:00
|
|
|
import Post from '../../../models/post';
|
|
|
|
import Like from '../../../models/like';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Aggregate like of a post
|
|
|
|
*
|
2017-03-01 09:37:01 +01:00
|
|
|
* @param {any} params
|
|
|
|
* @return {Promise<any>}
|
2016-12-28 23:49:51 +01:00
|
|
|
*/
|
2017-03-03 20:28:38 +01:00
|
|
|
module.exports = (params) => new Promise(async (res, rej) => {
|
2016-12-28 23:49:51 +01:00
|
|
|
// Get 'post_id' parameter
|
2017-03-03 11:52:36 +01:00
|
|
|
const [postId, postIdErr] = it(params.post_id).expect.id().required().qed();
|
|
|
|
if (postIdErr) return rej('invalid post_id param');
|
2016-12-28 23:49:51 +01:00
|
|
|
|
|
|
|
// Lookup post
|
|
|
|
const post = await Post.findOne({
|
2017-03-03 11:52:36 +01:00
|
|
|
_id: postId
|
2016-12-28 23:49:51 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
if (post === null) {
|
|
|
|
return rej('post not found');
|
|
|
|
}
|
|
|
|
|
|
|
|
const datas = await Like
|
|
|
|
.aggregate([
|
|
|
|
{ $match: { post_id: post._id } },
|
|
|
|
{ $project: {
|
|
|
|
created_at: { $add: ['$created_at', 9 * 60 * 60 * 1000] } // Convert into JST
|
|
|
|
}},
|
|
|
|
{ $project: {
|
|
|
|
date: {
|
|
|
|
year: { $year: '$created_at' },
|
|
|
|
month: { $month: '$created_at' },
|
|
|
|
day: { $dayOfMonth: '$created_at' }
|
|
|
|
}
|
|
|
|
}},
|
|
|
|
{ $group: {
|
|
|
|
_id: '$date',
|
|
|
|
count: { $sum: 1 }
|
|
|
|
}}
|
2017-01-17 03:11:22 +01:00
|
|
|
]);
|
2016-12-28 23:49:51 +01:00
|
|
|
|
|
|
|
datas.forEach(data => {
|
|
|
|
data.date = data._id;
|
|
|
|
delete data._id;
|
|
|
|
});
|
|
|
|
|
|
|
|
const graph = [];
|
|
|
|
|
|
|
|
for (let i = 0; i < 30; i++) {
|
|
|
|
let day = new Date(new Date().setDate(new Date().getDate() - i));
|
|
|
|
|
|
|
|
const data = datas.filter(d =>
|
|
|
|
d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate()
|
|
|
|
)[0];
|
|
|
|
|
|
|
|
if (data) {
|
2017-03-03 20:28:38 +01:00
|
|
|
graph.push(data);
|
2016-12-28 23:49:51 +01:00
|
|
|
} else {
|
|
|
|
graph.push({
|
|
|
|
date: {
|
|
|
|
year: day.getFullYear(),
|
|
|
|
month: day.getMonth() + 1, // In JavaScript, month is zero-based.
|
|
|
|
day: day.getDate()
|
|
|
|
},
|
|
|
|
count: 0
|
2017-03-03 20:28:38 +01:00
|
|
|
});
|
|
|
|
}
|
2016-12-28 23:49:51 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
res(graph);
|
|
|
|
});
|