diff --git a/src/routes/api/index.js b/src/routes/api/index.js index 0433c69..1e52232 100644 --- a/src/routes/api/index.js +++ b/src/routes/api/index.js @@ -5,6 +5,7 @@ router.use('/profiles', require('./profiles')); router.use('/tracks', require('./tracks')); router.use('/tags', require('./tags')); router.use('/accounts', require('../../accounts/accounts.controller')); +router.use('/stats', require('./stats')); router.use(function (err, req, res, next) { if (err.name === 'ValidationError') { diff --git a/src/routes/api/stats.js b/src/routes/api/stats.js new file mode 100644 index 0000000..71b6b2f --- /dev/null +++ b/src/routes/api/stats.js @@ -0,0 +1,29 @@ +const router = require('express').Router(); +const mongoose = require('mongoose'); +const Track = mongoose.model('Track'); +const wrapRoute = require('../../_helpers/wrapRoute'); + +// round to this number of meters for privacy reasons +const TRACK_LENGTH_ROUNDING = 1000 + +router.get( + '/', + wrapRoute(async (req, res) => { + const [{totalTrackLength, totalPublicTrackLength}] = 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'}}}, + {$project: {publicTrackLength: true, trackLength: true}}, + {$group: {_id: "sum", totalTrackLength: {$sum: '$trackLength'}, totalPublicTrackLength: {$sum: '$publicTrackLength'}}}, + ]) + + const totalTrackLengthPrivatized = Math.floor(totalTrackLength / TRACK_LENGTH_ROUNDING) * TRACK_LENGTH_ROUNDING; + + return res.json({ + totalTrackLength: totalTrackLengthPrivatized , + totalPublicTrackLength, + }); + }) +); + +module.exports = router;