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

78 lines
2 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-23 18:19:05 +00:00
import { getRequestFilters, 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;
2024-04-23 18:19:05 +00:00
referrer?: string;
title?: string;
os?: string;
browser?: string;
device?: string;
country?: string;
region: string;
city?: string;
2022-11-15 21:21:14 +00:00
}
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(),
2024-04-23 18:19:05 +00:00
referrer: yup.string(),
title: yup.string(),
os: yup.string(),
browser: yup.string(),
device: yup.string(),
country: yup.string(),
region: yup.string(),
city: yup.string(),
2023-08-20 05:23:15 +00:00
}),
};
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-04-23 18:19:05 +00:00
const { websiteId, timezone } = 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);
}
2024-04-23 18:19:05 +00:00
const filters = {
...getRequestFilters(req),
2022-11-15 21:21:14 +00:00
startDate,
endDate,
2022-12-29 22:51:51 +00:00
timezone,
2022-11-15 21:21:14 +00:00
unit,
2024-04-23 18:19:05 +00:00
};
const events = await getEventMetrics(websiteId, filters);
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
};