umami/pages/api/realtime/[id].ts

40 lines
1,008 B
TypeScript
Raw Normal View History

2023-02-15 10:27:18 +00:00
import { subMinutes } from 'date-fns';
2023-05-22 22:38:03 +00:00
import { canViewWebsite } from 'lib/auth';
2023-02-15 10:27:18 +00:00
import { useAuth } 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-05-22 22:38:03 +00:00
export interface RealtimeRequestQuery {
id: string;
startAt: number;
}
export default async (
req: NextApiRequestQueryBody<RealtimeRequestQuery>,
res: NextApiResponse<RealtimeInit>,
) => {
2023-02-15 10:27:18 +00:00
await useAuth(req, res);
if (req.method === 'GET') {
2023-05-22 22:38:03 +00:00
const { id: websiteId, startAt } = req.query;
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2023-02-18 05:42:42 +00:00
let startTime = subMinutes(new Date(), 30);
2023-02-15 10:27:18 +00:00
2023-02-18 05:42:42 +00:00
if (+startAt > startTime.getTime()) {
startTime = new Date(+startAt);
}
2023-05-22 22:38:03 +00:00
const data = await getRealtimeData(websiteId, startTime);
2023-02-15 10:27:18 +00:00
return ok(res, data);
}
return methodNotAllowed(res);
};