umami/pages/api/reports/event-data.ts

79 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-06-03 06:10:59 +00:00
import { canViewWebsite } from 'lib/auth';
import { useCors, useAuth } from 'lib/middleware';
import { NextApiRequestQueryBody } from 'lib/types';
import { NextApiResponse } from 'next';
import { ok, methodNotAllowed, unauthorized } from 'next-basics';
import { getEventDataFields } from 'queries/analytics/eventData/getEventDataFields';
2023-07-05 05:51:23 +00:00
import { getEventData } from 'queries';
2023-06-03 06:10:59 +00:00
export interface EventDataRequestBody {
websiteId: string;
dateRange: {
startDate: string;
endDate: string;
};
2023-07-05 05:51:23 +00:00
fields: [
{
name: string;
type: string;
value: string;
},
];
filters: [
{
name: string;
type: string;
value: string;
},
];
groups: [
{
name: string;
type: string;
},
];
2023-06-03 06:10:59 +00:00
}
export default async (
req: NextApiRequestQueryBody<any, EventDataRequestBody>,
2023-07-05 05:51:23 +00:00
res: NextApiResponse<any>,
2023-06-03 06:10:59 +00:00
) => {
await useCors(req, res);
await useAuth(req, res);
if (req.method === 'GET') {
const { websiteId, startAt, endAt } = req.query;
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
const data = await getEventDataFields(websiteId, new Date(+startAt), new Date(+endAt));
return ok(res, data);
}
if (req.method === 'POST') {
const {
websiteId,
dateRange: { startDate, endDate },
2023-07-05 05:51:23 +00:00
...criteria
2023-06-03 06:10:59 +00:00
} = req.body;
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2023-07-05 05:51:23 +00:00
const data = await getEventData(
websiteId,
new Date(startDate),
new Date(endDate),
criteria as any,
);
2023-06-03 06:10:59 +00:00
return ok(res, data);
}
return methodNotAllowed(res);
};