umami/src/pages/api/realtime/[websiteId].ts

46 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-12-10 04:55:50 +00:00
import { startOfMinute, subMinutes } from 'date-fns';
2023-05-22 22:38:03 +00:00
import { canViewWebsite } from 'lib/auth';
2023-08-20 05:23:15 +00:00
import { useAuth, useValidate } from 'lib/middleware';
2023-05-22 22:38:03 +00:00
import { NextApiRequestQueryBody, RealtimeInit } from 'lib/types';
2023-02-15 10:27:18 +00:00
import { NextApiResponse } from 'next';
2023-05-22 22:38:03 +00:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
2023-02-15 10:27:18 +00:00
import { getRealtimeData } from 'queries';
2023-08-20 05:23:15 +00:00
import * as yup from 'yup';
2023-12-10 04:55:50 +00:00
import { REALTIME_RANGE } from 'lib/constants';
2023-05-22 22:38:03 +00:00
export interface RealtimeRequestQuery {
2024-02-01 06:08:48 +00:00
websiteId: string;
2024-06-20 04:47:27 +00:00
timezone: string;
2023-05-22 22:38:03 +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(),
2024-06-20 04:47:27 +00:00
timezone: yup.string().required(),
2023-08-20 05:23:15 +00:00
}),
};
2023-05-22 22:38:03 +00:00
export default async (
req: NextApiRequestQueryBody<RealtimeRequestQuery>,
res: NextApiResponse<RealtimeInit>,
) => {
2023-02-15 10:27:18 +00:00
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
2023-02-15 10:27:18 +00:00
if (req.method === 'GET') {
2024-06-20 04:47:27 +00:00
const { websiteId, timezone } = req.query;
2023-05-22 22:38:03 +00:00
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2024-06-20 04:47:27 +00:00
const startDate = subMinutes(startOfMinute(new Date()), REALTIME_RANGE);
2023-02-15 10:27:18 +00:00
2024-06-20 04:47:27 +00:00
const data = await getRealtimeData(websiteId, { startDate, timezone });
2023-02-15 10:27:18 +00:00
return ok(res, data);
}
return methodNotAllowed(res);
};