2021-02-27 04:50:44 +01:00
|
|
|
import { getPageviewMetrics, getSessionMetrics, getWebsiteById } from 'lib/queries';
|
|
|
|
import { ok, methodNotAllowed, unauthorized, badRequest } from 'lib/response';
|
2020-09-18 07:52:20 +02:00
|
|
|
import { allowQuery } from 'lib/auth';
|
2020-07-28 08:52:14 +02:00
|
|
|
|
2020-10-09 00:02:48 +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') {
|
2020-12-05 05:45:12 +01:00
|
|
|
return `concat(event_type, '\t', event_value)`;
|
2020-10-09 00:02:48 +02:00
|
|
|
}
|
|
|
|
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') {
|
2020-09-18 07:52:20 +02:00
|
|
|
if (!(await allowQuery(req))) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2021-02-27 04:50:44 +01:00
|
|
|
const { id, type, start_at, end_at, url } = req.query;
|
2020-09-18 07:52:20 +02:00
|
|
|
|
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
|
|
|
|
2020-10-09 00:02:48 +02:00
|
|
|
if (sessionColumns.includes(type)) {
|
|
|
|
const data = await getSessionMetrics(websiteId, startDate, endDate, type, { url });
|
2020-07-30 06:40:26 +02:00
|
|
|
|
2020-10-09 00:02:48 +02:00
|
|
|
return ok(res, data);
|
|
|
|
}
|
|
|
|
|
2021-02-27 04:50:44 +01:00
|
|
|
if (pageviewColumns.includes(type) || type === 'event') {
|
|
|
|
let domain;
|
|
|
|
if (type === 'referrer') {
|
|
|
|
const website = getWebsiteById(websiteId);
|
|
|
|
|
|
|
|
if (!website) {
|
|
|
|
return badRequest(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
domain = website.domain;
|
|
|
|
}
|
|
|
|
|
2020-10-09 00:02:48 +02:00
|
|
|
const data = await getPageviewMetrics(
|
|
|
|
websiteId,
|
|
|
|
startDate,
|
|
|
|
endDate,
|
|
|
|
getColumn(type),
|
|
|
|
getTable(type),
|
|
|
|
{
|
2021-02-27 04:50:44 +01:00
|
|
|
domain,
|
2020-10-09 00:02:48 +02:00
|
|
|
url: type !== 'url' && url,
|
|
|
|
},
|
|
|
|
);
|
2020-09-11 22:49:43 +02:00
|
|
|
|
2020-10-09 00:02:48 +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
|
|
|
};
|