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

57 lines
1.4 KiB
TypeScript
Raw Normal View History

import { WebsiteMetric, NextApiRequestQueryBody } from 'lib/types';
import { canViewWebsite } from 'lib/auth';
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;
2022-12-27 02:36:48 +01:00
startAt: string;
endAt: string;
2022-11-15 22:21:14 +01:00
unit: string;
2022-12-29 23:51:51 +01:00
timezone: string;
2022-11-15 22:21:14 +01:00
url: string;
2022-12-27 02:36:48 +01:00
eventName: string;
2022-11-15 22:21:14 +01:00
}
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-12-29 23:51:51 +01:00
const { id: websiteId, startAt, endAt, unit, timezone, url, eventName } = req.query;
2022-10-12 22:11:44 +02:00
if (req.method === 'GET') {
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2022-12-29 23:51:51 +01:00
if (!moment.tz.zone(timezone) || !unitTypes.includes(unit)) {
2020-09-11 22:49:43 +02:00
return badRequest(res);
}
2022-12-27 02:36:48 +01:00
const startDate = new Date(+startAt);
const endDate = new Date(+endAt);
2020-08-27 12:42:24 +02:00
2022-11-15 22:21:14 +01:00
const events = await getEventMetrics(websiteId, {
startDate,
endDate,
2022-12-29 23:51:51 +01:00
timezone,
2022-11-15 22:21:14 +01:00
unit,
filters: {
url,
2022-12-27 02:36:48 +01:00
eventName,
2022-11-15 22:21:14 +01:00
},
});
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
};