umami/src/pages/api/event-data/events.ts

54 lines
1.3 KiB
TypeScript
Raw Normal View History

import { canViewWebsite } from 'lib/auth';
2023-08-20 05:23:15 +00:00
import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody } from 'lib/types';
import { NextApiResponse } from 'next';
2023-08-20 05:23:15 +00:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getEventDataEvents } from 'queries';
2023-08-20 05:23:15 +00:00
import * as yup from 'yup';
2023-08-20 05:23:15 +00:00
export interface EventDataFieldsRequestQuery {
websiteId: string;
2023-08-20 05:23:15 +00:00
startAt: string;
endAt: string;
2023-08-24 19:55:15 +00:00
event?: string;
}
2023-08-20 05:23:15 +00:00
const schema = {
GET: yup.object().shape({
websiteId: yup.string().uuid().required(),
startAt: yup.number().integer().required(),
endAt: yup.number().integer().min(yup.ref('startAt')).required(),
2023-08-24 19:55:15 +00:00
event: yup.string(),
2023-08-20 05:23:15 +00:00
}),
};
export default async (
2023-08-20 05:23:15 +00:00
req: NextApiRequestQueryBody<EventDataFieldsRequestQuery, any>,
res: NextApiResponse<any>,
) => {
await useCors(req, res);
await useAuth(req, res);
2023-09-30 03:24:48 +00:00
await useValidate(schema, req, res);
2023-08-20 05:23:15 +00:00
if (req.method === 'GET') {
2023-08-07 19:43:43 +00:00
const { websiteId, startAt, endAt, event } = req.query;
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2023-08-04 22:21:14 +00:00
const startDate = new Date(+startAt);
const endDate = new Date(+endAt);
const data = await getEventDataEvents(websiteId, {
startDate,
endDate,
2023-08-07 19:43:43 +00:00
event,
});
return ok(res, data);
}
return methodNotAllowed(res);
};