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;
|
2023-05-22 22:38:03 +00:00
|
|
|
startAt: number;
|
|
|
|
|
}
|
|
|
|
|
|
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-25 18:33:30 +00:00
|
|
|
startAt: yup.number().integer().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-02-01 06:08:48 +00:00
|
|
|
const { websiteId, startAt } = req.query;
|
2023-05-22 22:38:03 +00:00
|
|
|
|
|
|
|
|
if (!(await canViewWebsite(req.auth, websiteId))) {
|
|
|
|
|
return unauthorized(res);
|
|
|
|
|
}
|
|
|
|
|
|
2023-12-10 04:55:50 +00:00
|
|
|
let startTime = subMinutes(startOfMinute(new Date()), REALTIME_RANGE);
|
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);
|
|
|
|
|
};
|