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

41 lines
1.1 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';
2024-06-20 05:12:35 +00:00
import { NextApiRequestQueryBody } 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;
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(),
2023-08-20 05:23:15 +00:00
}),
};
2024-06-20 05:12:35 +00:00
export default async (req: NextApiRequestQueryBody<RealtimeRequestQuery>, res: NextApiResponse) => {
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-08-21 06:58:20 +00:00
const { websiteId } = 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-08-21 06:58:20 +00:00
const data = await getRealtimeData(websiteId, { startDate });
2023-02-15 10:27:18 +00:00
return ok(res, data);
}
return methodNotAllowed(res);
};