2020-09-25 09:15:58 +02:00
|
|
|
import { getPageviewMetrics, getSessionMetrics } from 'lib/queries';
|
2020-09-18 07:52:20 +02:00
|
|
|
import { ok, badRequest, methodNotAllowed, unauthorized } from 'lib/response';
|
2020-09-11 22:49:43 +02:00
|
|
|
import { DOMAIN_REGEX } from 'lib/constants';
|
2020-09-18 07:52:20 +02:00
|
|
|
import { allowQuery } from 'lib/auth';
|
2020-08-01 04:05:14 +02:00
|
|
|
|
2020-08-07 04:37:19 +02:00
|
|
|
const sessionColumns = ['browser', 'os', 'device', 'country'];
|
2020-08-01 04:05:14 +02:00
|
|
|
const pageviewColumns = ['url', 'referrer'];
|
|
|
|
|
2020-08-28 03:44:20 +02:00
|
|
|
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-08-01 04:05: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);
|
|
|
|
}
|
|
|
|
|
2020-09-11 22:49:43 +02:00
|
|
|
const { id, type, start_at, end_at, domain } = req.query;
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2020-09-25 09:15:58 +02:00
|
|
|
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-09-25 09:15:58 +02:00
|
|
|
if (sessionColumns.includes(type)) {
|
|
|
|
const data = await getSessionMetrics(websiteId, startDate, endDate, type);
|
|
|
|
|
|
|
|
return ok(res, data);
|
2020-09-11 22:49:43 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 09:15:58 +02:00
|
|
|
if (type === 'event' || pageviewColumns.includes(type)) {
|
|
|
|
const data = await getPageviewMetrics(
|
|
|
|
websiteId,
|
|
|
|
startDate,
|
|
|
|
endDate,
|
|
|
|
getColumn(type),
|
|
|
|
getTable(type),
|
|
|
|
domain,
|
|
|
|
);
|
2020-09-11 22:49:43 +02:00
|
|
|
|
2020-09-25 09:15:58 +02:00
|
|
|
return ok(res, data);
|
|
|
|
}
|
2020-08-01 04:05:14 +02:00
|
|
|
}
|
|
|
|
|
2020-09-11 22:49:43 +02:00
|
|
|
return methodNotAllowed(res);
|
2020-08-01 04:05:14 +02:00
|
|
|
};
|