unpkg/modules/actions/serveStats.js

62 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-07-10 20:24:27 +00:00
import { subDays, startOfDay } from 'date-fns';
2018-06-02 05:34:56 +00:00
import getStats from '../utils/getStats.js';
2017-11-11 20:18:13 +00:00
export default function serveStats(req, res) {
2018-02-18 02:00:56 +00:00
let since, until;
2019-01-06 00:50:05 +00:00
if (req.query.period) {
switch (req.query.period) {
case 'last-day':
until = startOfDay(new Date());
since = subDays(until, 1);
break;
case 'last-week':
until = startOfDay(new Date());
since = subDays(until, 7);
break;
case 'last-month':
default:
until = startOfDay(new Date());
since = subDays(until, 30);
}
} else {
until = req.query.until
? new Date(req.query.until)
2019-07-10 20:24:27 +00:00
: startOfDay(new Date());
since = req.query.since ? new Date(req.query.since) : subDays(until, 1);
2017-11-11 20:18:13 +00:00
}
if (isNaN(since.getTime())) {
2018-12-17 17:38:05 +00:00
return res.status(403).send({ error: '?since is not a valid date' });
2017-11-11 20:18:13 +00:00
}
if (isNaN(until.getTime())) {
2018-12-17 17:38:05 +00:00
return res.status(403).send({ error: '?until is not a valid date' });
2017-11-11 20:18:13 +00:00
}
if (until <= since) {
2018-02-18 02:00:56 +00:00
return res
.status(403)
2018-12-17 17:38:05 +00:00
.send({ error: '?until date must come after ?since date' });
2017-11-11 20:18:13 +00:00
}
if (until >= new Date()) {
2018-12-17 17:38:05 +00:00
return res.status(403).send({ error: '?until must be a date in the past' });
2017-11-11 20:18:13 +00:00
}
2019-01-06 00:50:05 +00:00
getStats(since, until).then(
2017-11-11 20:18:13 +00:00
stats => {
res
.set({
2019-01-08 14:47:04 +00:00
'Cache-Control': 'public, max-age=3600', // 1 hour
2018-12-17 17:38:05 +00:00
'Cache-Tag': 'stats'
2017-11-11 20:18:13 +00:00
})
2018-02-18 02:00:56 +00:00
.send(stats);
2017-11-11 20:18:13 +00:00
},
error => {
2018-02-18 02:00:56 +00:00
console.error(error);
2018-12-17 17:38:05 +00:00
res.status(500).send({ error: 'Unable to fetch stats' });
2017-11-11 20:18:13 +00:00
}
2018-02-18 02:00:56 +00:00
);
2017-11-11 20:18:13 +00:00
}