umami/src/pages/api/websites/[id]/reports.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-10-15 04:59:54 +00:00
import * as yup from 'yup';
2023-08-14 05:21:49 +00:00
import { canViewWebsite } from 'lib/auth';
2023-08-20 05:23:15 +00:00
import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, SearchFilter } from 'lib/types';
2023-08-14 05:21:49 +00:00
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getReportsByWebsiteId } from 'queries';
2023-10-16 00:59:19 +00:00
import { pageInfo } from 'lib/schema';
2023-08-14 05:21:49 +00:00
export interface ReportsRequestQuery extends SearchFilter {
2023-08-14 05:21:49 +00:00
id: string;
}
2023-08-20 05:23:15 +00:00
const schema = {
GET: yup.object().shape({
id: yup.string().uuid().required(),
2023-10-16 00:59:19 +00:00
...pageInfo,
2023-08-20 05:23:15 +00:00
}),
};
2023-08-14 05:21:49 +00:00
export default async (
req: NextApiRequestQueryBody<ReportsRequestQuery, any>,
res: NextApiResponse,
) => {
await useCors(req, res);
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-08-14 05:21:49 +00:00
const { id: websiteId } = req.query;
if (req.method === 'GET') {
2023-10-16 00:59:19 +00:00
if (!(await canViewWebsite(req.auth, websiteId))) {
2023-08-14 05:21:49 +00:00
return unauthorized(res);
}
2023-10-16 00:59:19 +00:00
const { page, query, pageSize } = req.query;
2023-08-14 05:21:49 +00:00
const data = await getReportsByWebsiteId(websiteId, {
page,
2023-10-16 00:59:19 +00:00
pageSize: +pageSize || undefined,
query,
2023-08-14 05:21:49 +00:00
});
return ok(res, data);
}
return methodNotAllowed(res);
};