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

61 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-08-28 03:44:20 +02:00
import { getRankings } from 'lib/queries';
2020-09-11 22:49:43 +02:00
import { ok, badRequest, methodNotAllowed } from 'lib/response';
import { DOMAIN_REGEX } from 'lib/constants';
import { useAuth } from 'lib/middleware';
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
await useAuth(req, res);
if (req.method === 'GET') {
const { id, type, start_at, end_at, domain } = req.query;
const websiteId = +id;
const startDate = new Date(+start_at);
const endDate = new Date(+end_at);
if (
type !== 'event' &&
!sessionColumns.includes(type) &&
!pageviewColumns.includes(type) &&
domain &&
DOMAIN_REGEX.test(domain)
) {
return badRequest(res);
}
const rankings = await getRankings(
websiteId,
startDate,
endDate,
getColumn(type),
getTable(type),
domain,
);
return ok(res, rankings);
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
};