Format /stats handler, add trackDuration, fix for mongod version <4.4

This commit is contained in:
Paul Bienkowski 2021-02-12 21:54:48 +01:00
parent 5fa856c4ea
commit 67bae58b54

View file

@ -5,42 +5,62 @@ const User = mongoose.model('User');
const wrapRoute = require('../../_helpers/wrapRoute');
// round to this number of meters for privacy reasons
const TRACK_LENGTH_ROUNDING = 1000
const TRACK_LENGTH_ROUNDING = 1000;
router.get(
'/',
wrapRoute(async (req, res) => {
const trackCount = await Track.find().count()
const publicTrackCount = await Track.find({visible: true}).count()
const userCount = await User.find().count()
const trackCount = await Track.find().count();
const publicTrackCount = await Track.find({ visible: true }).count();
const userCount = await User.find().count();
const [{trackLength, publicTrackLength, numEvents}] = await Track.aggregate([
{$lookup: { from: 'trackdatas', localField: 'publicTrackData', foreignField: '_id', as: 'publicTrackDatas' }},
{$lookup: { from: 'trackdatas', localField: 'trackData', foreignField: '_id', as: 'trackDatas' }},
{$addFields: {
publicTrackLength: {$first: '$publicTrackDatas.trackLength'},
trackLength: {$first: '$trackDatas.trackLength'},
numEvents: {$first: '$publicTrackDatas.numEvents'},
}},
{$project: {publicTrackLength: true, trackLength: true, numEvents: true}},
{$group: {_id: "sum",
trackLength: {$sum: '$trackLength'},
publicTrackLength: {$sum: '$publicTrackLength'},
numEvents: {$sum: '$numEvents'},
}},
])
const [{ trackLength, publicTrackLength, numEvents, trackDuration }] = await Track.aggregate([
{ $lookup: { from: 'trackdatas', localField: 'publicTrackData', foreignField: '_id', as: 'publicTrackDatas' } },
{ $lookup: { from: 'trackdatas', localField: 'trackData', foreignField: '_id', as: 'trackDatas' } },
{
$addFields: {
publicTrackData: { $arrayElemAt: ['$publicTrackDatas', 0] },
trackData: { $arrayElemAt: ['$trackDatas', 0] },
},
},
{
$addFields: {
publicTrackLength: '$publicTrackData.trackLength',
trackLength: '$trackData.trackLength',
numEvents: '$publicTrackData.numEvents',
trackDuration: {
$cond: [
{ $and: ['$publicTrackData.recordedUntil', '$publicTrackData.recordedAt'] },
{ $subtract: ['$publicTrackData.recordedUntil', '$publicTrackData.recordedAt'] },
0,
],
},
},
},
{ $project: { publicTrackLength: true, trackLength: true, numEvents: true, trackDuration: true } },
{
$group: {
_id: 'sum',
trackLength: { $sum: '$trackLength' },
publicTrackLength: { $sum: '$publicTrackLength' },
numEvents: { $sum: '$numEvents' },
trackDuration: { $sum: '$trackDuration' },
},
},
]);
const trackLengthPrivatized = Math.floor(trackLength / TRACK_LENGTH_ROUNDING) * TRACK_LENGTH_ROUNDING;
return res.json({
publicTrackCount,
publicTrackLength,
trackLength: trackLengthPrivatized ,
trackLength: trackLengthPrivatized,
numEvents,
trackCount,
trackDuration: Math.round(trackDuration / 1000),
userCount,
});
})
}),
);
module.exports = router;