Renamed id routes for API.

This commit is contained in:
Mike Cao
2024-01-31 22:08:48 -08:00
parent 53a991176b
commit 4429198397
42 changed files with 154 additions and 170 deletions

View File

@@ -0,0 +1,49 @@
import { startOfMinute, subMinutes } from 'date-fns';
import { canViewWebsite } from 'lib/auth';
import { useAuth, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, RealtimeInit } from 'lib/types';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getRealtimeData } from 'queries';
import * as yup from 'yup';
import { REALTIME_RANGE } from 'lib/constants';
export interface RealtimeRequestQuery {
websiteId: string;
startAt: number;
}
const schema = {
GET: yup.object().shape({
websiteId: yup.string().uuid().required(),
startAt: yup.number().integer().required(),
}),
};
export default async (
req: NextApiRequestQueryBody<RealtimeRequestQuery>,
res: NextApiResponse<RealtimeInit>,
) => {
await useAuth(req, res);
await useValidate(schema, req, res);
if (req.method === 'GET') {
const { websiteId, startAt } = req.query;
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
let startTime = subMinutes(startOfMinute(new Date()), REALTIME_RANGE);
if (+startAt > startTime.getTime()) {
startTime = new Date(+startAt);
}
const data = await getRealtimeData(websiteId, startTime);
return ok(res, data);
}
return methodNotAllowed(res);
};