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;
|
|
|
|
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-12-02 05:53:37 +01:00
|
|
|
const {
|
|
|
|
user: { id: userId },
|
|
|
|
} = req.auth;
|
|
|
|
const { id: websiteId, start_at, end_at, unit, tz, url, event_name } = req.query;
|
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
if (req.method === 'GET') {
|
2022-12-02 05:53:37 +01:00
|
|
|
if (canViewWebsite(userId, websiteId)) {
|
2020-09-18 07:52:20 +02:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
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,
|
|
|
|
},
|
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
|
|
|
};
|