rudeshark.net/src/api/endpoints/aggregation/posts/reply.ts

76 lines
1.5 KiB
TypeScript
Raw Normal View History

2016-12-28 23:49:51 +01:00
/**
* Module dependencies
*/
2017-03-08 19:50:09 +01:00
import $ from 'cafy';
2016-12-28 23:49:51 +01:00
import Post from '../../../models/post';
/**
* Aggregate reply 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-08 19:50:09 +01:00
const [postId, postIdErr] = $(params.post_id).id().$;
2017-03-03 11:52:36 +01:00
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 Post
.aggregate([
{ $match: { reply_to: 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);
});