umami/pages/api/websites/[id]/events.ts

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-11-15 22:21:14 +01:00
import { WebsiteMetric } from 'interface/api/models';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { allowQuery } from 'lib/auth';
import { TYPE_WEBSITE } from 'lib/constants';
2022-11-15 22:21:14 +01:00
import { useAuth, useCors } from 'lib/middleware';
import moment from 'moment-timezone';
import { NextApiResponse } from 'next';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getEventMetrics } from 'queries';
2020-08-27 12:42:24 +02:00
const unitTypes = ['year', 'month', 'hour', 'day'];
2020-08-27 12:42:24 +02:00
2022-11-15 22:21:14 +01:00
export interface WebsiteEventsRequestQuery {
id: string;
start_at: string;
end_at: string;
unit: string;
tz: string;
url: string;
event_name: string;
}
export default async (
req: NextApiRequestQueryBody<WebsiteEventsRequestQuery>,
res: NextApiResponse<WebsiteMetric>,
) => {
2022-10-12 22:11:44 +02:00
await useCors(req, res);
await useAuth(req, res);
2022-04-04 09:33:20 +02:00
2022-10-12 22:11:44 +02:00
if (req.method === 'GET') {
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}
2022-10-12 04:37:38 +02:00
const { id: websiteId, start_at, end_at, unit, tz, url, event_name } = req.query;
2020-09-11 22:49:43 +02:00
if (!moment.tz.zone(tz) || !unitTypes.includes(unit)) {
return badRequest(res);
}
const startDate = new Date(+start_at);
const endDate = new Date(+end_at);
2020-08-27 12:42:24 +02:00
2022-11-15 22:21:14 +01:00
const events = await getEventMetrics(websiteId, {
startDate,
endDate,
timezone: tz,
unit,
filters: {
url,
eventName: event_name,
},
});
2020-09-11 22:49:43 +02:00
return ok(res, events);
}
2020-08-27 12:42:24 +02:00
2020-09-11 22:49:43 +02:00
return methodNotAllowed(res);
2020-08-27 12:42:24 +02:00
};