unpkg/modules/actions/showStats.js

64 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-02-18 02:00:56 +00:00
const subDays = require("date-fns/sub_days");
const startOfDay = require("date-fns/start_of_day");
const startOfSecond = require("date-fns/start_of_second");
2018-06-02 05:34:56 +00:00
2018-02-18 02:00:56 +00:00
const StatsAPI = require("../StatsAPI");
2017-11-11 20:18:13 +00:00
function showStats(req, res) {
2018-02-18 02:00:56 +00:00
let since, until;
2017-11-11 20:18:13 +00:00
switch (req.query.period) {
2017-11-25 21:25:01 +00:00
case "last-day":
2018-02-18 02:00:56 +00:00
until = startOfDay(new Date());
since = subDays(until, 1);
break;
2017-11-25 21:25:01 +00:00
case "last-week":
2018-02-18 02:00:56 +00:00
until = startOfDay(new Date());
since = subDays(until, 7);
break;
2017-11-25 21:25:01 +00:00
case "last-month":
2018-02-18 02:00:56 +00:00
until = startOfDay(new Date());
since = subDays(until, 30);
break;
2017-11-11 20:18:13 +00:00
default:
2018-02-18 02:00:56 +00:00
until = req.query.until
? new Date(req.query.until)
: startOfSecond(new Date());
since = new Date(req.query.since);
2017-11-11 20:18:13 +00:00
}
if (isNaN(since.getTime())) {
2018-02-18 02:00:56 +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-02-18 02:00:56 +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)
.send({ error: "?until date must come after ?since date" });
2017-11-11 20:18:13 +00:00
}
if (until >= new Date()) {
2018-02-18 02:00:56 +00:00
return res.status(403).send({ error: "?until must be a date in the past" });
2017-11-11 20:18:13 +00:00
}
StatsAPI.getStats(since, until).then(
stats => {
res
.set({
2017-11-25 21:25:01 +00:00
"Cache-Control": "public, max-age=60",
"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);
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
}
2018-02-18 02:00:56 +00:00
module.exports = showStats;