umami/pages/api/website/[id]/metrics.js

69 lines
1.5 KiB
JavaScript
Raw Normal View History

import { getPageviewMetrics, getSessionMetrics } from 'lib/queries';
import { ok, badRequest, methodNotAllowed, unauthorized } from 'lib/response';
import { DOMAIN_REGEX } from 'lib/constants';
import { allowQuery } from 'lib/auth';
2020-07-28 08:52:14 +02:00
const sessionColumns = ['browser', 'os', 'device', 'country'];
const pageviewColumns = ['url', 'referrer'];
function getTable(type) {
if (type === 'event') {
return 'event';
}
if (sessionColumns.includes(type)) {
return 'session';
}
return 'pageview';
}
function getColumn(type) {
if (type === 'event') {
return `concat(event_type, ':', event_value)`;
}
return type;
}
2020-07-28 08:52:14 +02:00
export default async (req, res) => {
2020-09-11 22:49:43 +02:00
if (req.method === 'GET') {
if (!(await allowQuery(req))) {
return unauthorized(res);
}
const { id, type, start_at, end_at, domain, url } = req.query;
if (domain && !DOMAIN_REGEX.test(domain)) {
return badRequest(res);
}
2020-09-11 22:49:43 +02:00
const websiteId = +id;
const startDate = new Date(+start_at);
const endDate = new Date(+end_at);
2020-07-28 08:52:14 +02:00
if (sessionColumns.includes(type)) {
const data = await getSessionMetrics(websiteId, startDate, endDate, type, { url });
return ok(res, data);
}
if (type === 'event' || pageviewColumns.includes(type)) {
const data = await getPageviewMetrics(
websiteId,
startDate,
endDate,
getColumn(type),
getTable(type),
{
domain,
url: type !== 'url' && url,
},
);
2020-09-11 22:49:43 +02:00
return ok(res, data);
}
2020-09-11 22:49:43 +02:00
}
return methodNotAllowed(res);
2020-07-28 08:52:14 +02:00
};