umami/pages/api/reports/index.ts

64 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-08-10 22:26:33 +02:00
import { canViewWebsite } from 'lib/auth';
import { uuid } from 'lib/crypto';
2023-05-18 22:13:18 +02:00
import { useAuth, useCors } from 'lib/middleware';
2023-08-10 22:26:33 +02:00
import { NextApiRequestQueryBody, ReportSearchFilterType, SearchFilter } from 'lib/types';
2023-05-18 22:13:18 +02:00
import { NextApiResponse } from 'next';
2023-07-29 02:52:57 +02:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
2023-08-14 07:21:49 +02:00
import { createReport, getReportsByUserId, getReportsByWebsiteId } from 'queries';
2023-08-10 22:26:33 +02:00
export interface ReportsRequestQuery extends SearchFilter<ReportSearchFilterType> {}
2023-05-18 22:13:18 +02:00
export interface ReportRequestBody {
2023-05-18 22:13:18 +02:00
websiteId: string;
name: string;
type: string;
description: string;
parameters: {
window: string;
urls: string[];
};
2023-05-18 22:13:18 +02:00
}
export default async (
req: NextApiRequestQueryBody<any, ReportRequestBody>,
2023-05-18 22:13:18 +02:00
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);
const {
user: { id: userId },
} = req.auth;
if (req.method === 'GET') {
2023-08-10 22:26:33 +02:00
const { page, filter, pageSize } = req.query;
2023-08-14 07:21:49 +02:00
const data = await getReportsByUserId(userId, {
2023-08-10 22:26:33 +02:00
page,
filter,
pageSize: +pageSize || null,
2023-08-18 01:39:59 +02:00
includeTeams: true,
2023-08-10 22:26:33 +02:00
});
2023-05-18 22:13:18 +02:00
return ok(res, data);
}
if (req.method === 'POST') {
const { websiteId, type, name, description, parameters } = req.body;
const result = await createReport({
2023-05-18 22:13:18 +02:00
id: uuid(),
userId,
websiteId,
type,
name,
description,
parameters: JSON.stringify(parameters),
} as any);
return ok(res, result);
2023-05-18 22:13:18 +02:00
}
return methodNotAllowed(res);
};