2017-11-25 21:25:01 +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")
|
|
|
|
const StatsAPI = require("../StatsAPI")
|
2017-11-11 20:18:13 +00:00
|
|
|
|
|
|
|
function showStats(req, res) {
|
|
|
|
let since, until
|
|
|
|
switch (req.query.period) {
|
2017-11-25 21:25:01 +00:00
|
|
|
case "last-day":
|
2017-11-11 20:18:13 +00:00
|
|
|
until = startOfDay(new Date())
|
|
|
|
since = subDays(until, 1)
|
|
|
|
break
|
2017-11-25 21:25:01 +00:00
|
|
|
case "last-week":
|
2017-11-11 20:18:13 +00:00
|
|
|
until = startOfDay(new Date())
|
|
|
|
since = subDays(until, 7)
|
|
|
|
break
|
2017-11-25 21:25:01 +00:00
|
|
|
case "last-month":
|
2017-11-11 20:18:13 +00:00
|
|
|
until = startOfDay(new Date())
|
|
|
|
since = subDays(until, 30)
|
|
|
|
break
|
|
|
|
default:
|
2017-11-25 21:25:01 +00:00
|
|
|
until = req.query.until ? new Date(req.query.until) : startOfSecond(new Date())
|
2017-11-11 20:18:13 +00:00
|
|
|
since = new Date(req.query.since)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isNaN(since.getTime())) {
|
2017-11-25 21:25:01 +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())) {
|
2017-11-25 21:25:01 +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) {
|
2017-11-25 21:25:01 +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()) {
|
2017-11-25 21:25:01 +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
|
|
|
})
|
|
|
|
.send(stats)
|
|
|
|
},
|
|
|
|
error => {
|
|
|
|
console.error(error)
|
2017-11-25 21:25:01 +00:00
|
|
|
res.status(500).send({ error: "Unable to fetch stats" })
|
2017-11-11 20:18:13 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = showStats
|