umami/src/pages/api/websites/[websiteId]/events.ts

60 lines
1.5 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';
2024-04-03 00:06:06 +00:00
import { getRequestDateRange } from 'lib/request';
2023-09-25 20:31:25 +00:00
import { NextApiRequestQueryBody, WebsiteMetric } from 'lib/types';
import { TimezoneTest, UnitTypeTest } from 'lib/yup';
2022-11-15 21:21:14 +00:00
import { NextApiResponse } from 'next';
2023-09-25 20:31:25 +00:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
2022-11-15 21:21:14 +00:00
import { getEventMetrics } from 'queries';
2023-09-25 20:19:56 +00:00
import * as yup from 'yup';
2020-08-27 10:42:24 +00:00
2022-11-15 21:21:14 +00:00
export interface WebsiteEventsRequestQuery {
2024-02-01 06:08:48 +00:00
websiteId: string;
2022-12-27 01:36:48 +00:00
startAt: string;
endAt: string;
2023-09-25 20:31:25 +00:00
unit?: string;
timezone?: string;
2022-11-15 21:21:14 +00:00
url: string;
}
2023-08-20 05:23:15 +00:00
const schema = {
GET: yup.object().shape({
2024-02-01 06:08:48 +00:00
websiteId: yup.string().uuid().required(),
2023-08-20 05:23:15 +00:00
startAt: yup.number().integer().required(),
endAt: yup.number().integer().min(yup.ref('startAt')).required(),
2023-09-25 20:31:25 +00:00
unit: UnitTypeTest,
timezone: TimezoneTest,
2023-08-20 05:23:15 +00:00
url: yup.string(),
}),
};
2022-11-15 21:21:14 +00:00
export default async (
req: NextApiRequestQueryBody<WebsiteEventsRequestQuery>,
res: NextApiResponse<WebsiteMetric>,
) => {
2022-10-12 20:11:44 +00:00
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
2024-02-01 06:08:48 +00:00
const { websiteId, timezone, url } = req.query;
2024-04-03 00:06:06 +00:00
const { startDate, endDate, unit } = await getRequestDateRange(req);
2022-10-12 20:11:44 +00:00
if (req.method === 'GET') {
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2022-11-15 21:21:14 +00:00
const events = await getEventMetrics(websiteId, {
startDate,
endDate,
2022-12-29 22:51:51 +00:00
timezone,
2022-11-15 21:21:14 +00:00
unit,
2023-08-04 21:23:03 +00:00
url,
});
2020-09-11 20:49:43 +00:00
return ok(res, events);
}
2020-08-27 10:42:24 +00:00
2020-09-11 20:49:43 +00:00
return methodNotAllowed(res);
2020-08-27 10:42:24 +00:00
};