iceshrimp-legacy/src/server/api/endpoints/hashtags/trend.ts

83 lines
1.3 KiB
TypeScript
Raw Normal View History

2018-06-11 02:11:32 +02:00
import Note from '../../../../models/note';
/**
* Get trends of hashtags
*/
module.exports = (params, user) => new Promise(async (res, rej) => {
const data = await Note.aggregate([{
$match: {
createdAt: {
2018-06-11 04:24:29 +02:00
$gt: new Date(Date.now() - 1000 * 60 * 60)
2018-06-11 02:11:32 +02:00
},
tags: {
$exists: true,
$ne: []
}
}
}, {
$unwind: '$tags'
}, {
$group: {
_id: '$tags',
count: {
$sum: 1
}
}
}, {
$group: {
_id: null,
tags: {
$push: {
tag: '$_id',
count: '$count'
}
}
}
}, {
$project: {
_id: false,
tags: true
}
}]) as Array<{
tags: Array<{
tag: string;
count: number;
}>
}>;
2018-06-11 04:24:29 +02:00
if (data.length == 0) {
return res([]);
}
2018-06-11 02:11:32 +02:00
const hots = data[0].tags
.sort((a, b) => a.count - b.count)
.map(tag => tag.tag)
.slice(0, 10);
const countPromises: Array<Promise<number[]>> = [];
for (let i = 0; i < 10; i++) {
2018-06-11 04:24:29 +02:00
// 10分
const interval = 1000 * 60 * 10;
2018-06-11 02:11:32 +02:00
countPromises.push(Promise.all(hots.map(tag => Note.count({
tags: tag,
createdAt: {
$lt: new Date(Date.now() - (interval * i)),
$gt: new Date(Date.now() - (interval * (i + 1)))
}
}))));
}
const countsLog = await Promise.all(countPromises);
const stats = hots.map((tag, i) => ({
tag,
chart: countsLog.map(counts => counts[i])
}));
console.log(stats);
res(stats);
});