umami/pages/api/websites/[id]/stats.js

63 lines
1.6 KiB
JavaScript
Raw Normal View History

import { getWebsiteStats, getWebsiteById } from 'queries';
2022-08-29 05:20:54 +02:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth';
2022-04-04 09:33:20 +02:00
import { useCors } from 'lib/middleware';
export default async (req, res) => {
if (req.method === 'GET') {
2022-04-04 09:33:20 +02:00
await useCors(req, res);
if (!(await allowQuery(req))) {
return unauthorized(res);
}
const { website_id, start_at, end_at, url, referrer, os, browser, device, country } = req.query;
const websiteId = +website_id;
let websiteUuid = (await getWebsiteById(websiteId)).websiteUuid;
const startDate = new Date(+start_at);
const endDate = new Date(+end_at);
const distance = end_at - start_at;
const prevStartDate = new Date(+start_at - distance);
const prevEndDate = new Date(+end_at - distance);
const metrics = await getWebsiteStats(websiteUuid, {
2022-09-24 07:43:51 +02:00
start_at: startDate,
end_at: endDate,
filters: {
url,
referrer,
os,
browser,
device,
country,
},
2022-04-10 12:51:43 +02:00
});
const prevPeriod = await getWebsiteStats(websiteUuid, {
2022-09-24 07:43:51 +02:00
start_at: prevStartDate,
end_at: prevEndDate,
filters: {
url,
referrer,
os,
browser,
device,
country,
},
});
const stats = Object.keys(metrics[0]).reduce((obj, key) => {
obj[key] = {
value: Number(metrics[0][key]) || 0,
change: Number(metrics[0][key]) - Number(prevPeriod[0][key]) || 0,
};
return obj;
}, {});
return ok(res, stats);
}
return methodNotAllowed(res);
};