2023-07-10 13:35:19 +02: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';
|
2023-07-11 10:16:17 +02:00
|
|
|
import { getEventDataFields } from 'queries';
|
2023-07-10 13:35:19 +02:00
|
|
|
|
|
|
|
export interface EventDataRequestBody {
|
|
|
|
websiteId: string;
|
|
|
|
dateRange: {
|
|
|
|
startDate: string;
|
|
|
|
endDate: string;
|
|
|
|
};
|
|
|
|
field?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
|
|
|
req: NextApiRequestQueryBody<any, EventDataRequestBody>,
|
|
|
|
res: NextApiResponse<any>,
|
|
|
|
) => {
|
|
|
|
await useCors(req, res);
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
2023-07-11 10:16:17 +02:00
|
|
|
const { websiteId, startAt, endAt } = req.query;
|
2023-07-10 13:35:19 +02:00
|
|
|
|
|
|
|
if (!(await canViewWebsite(req.auth, websiteId))) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2023-07-11 10:16:17 +02:00
|
|
|
const results = await getEventDataFields(websiteId, new Date(+startAt), new Date(+endAt));
|
|
|
|
|
|
|
|
const data = results.reduce(
|
|
|
|
(obj, row) => {
|
2023-07-12 03:52:52 +02:00
|
|
|
obj.records += Number(row.total);
|
2023-07-11 10:16:17 +02:00
|
|
|
return obj;
|
|
|
|
},
|
2023-07-12 03:52:52 +02:00
|
|
|
{ fields: results.length, records: 0 },
|
2023-07-11 10:16:17 +02:00
|
|
|
);
|
2023-07-10 13:35:19 +02:00
|
|
|
|
|
|
|
return ok(res, data);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|