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