2022-12-09 08:43:43 +01:00
|
|
|
import { WebsiteMetric, NextApiRequestQueryBody } from 'lib/types';
|
2022-12-02 05:53:37 +01:00
|
|
|
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
|
|
|
|
2020-09-13 20:33:57 +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-12-02 05:53:37 +01:00
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
if (req.method === 'GET') {
|
2022-12-28 00:18:58 +01:00
|
|
|
if (!(await canViewWebsite(req.auth, websiteId))) {
|
2020-09-18 07:52:20 +02:00
|
|
|
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
|
|
|
},
|
2021-09-29 10:38:52 +02: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
|
|
|
};
|