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

79 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-07-30 09:11:26 +02:00
import { canUpdateReport, canViewReport, canDeleteReport } from 'lib/auth';
2023-05-18 22:13:18 +02:00
import { useAuth, useCors } from 'lib/middleware';
import { NextApiRequestQueryBody } from 'lib/types';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
2023-07-30 09:11:26 +02:00
import { getReportById, updateReport, deleteReport } from 'queries';
2023-05-18 22:13:18 +02:00
export interface ReportRequestQuery {
2023-05-18 22:13:18 +02:00
id: string;
}
export interface ReportRequestBody {
2023-05-18 22:13:18 +02:00
websiteId: string;
type: string;
name: string;
description: string;
2023-05-18 22:13:18 +02:00
parameters: string;
}
export default async (
req: NextApiRequestQueryBody<ReportRequestQuery, ReportRequestBody>,
2023-05-18 22:13:18 +02:00
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);
2023-07-30 09:11:26 +02:00
const { id: reportId } = req.query;
const {
user: { id: userId },
} = req.auth;
2023-05-18 22:13:18 +02:00
2023-07-30 09:11:26 +02:00
if (req.method === 'GET') {
const report = await getReportById(reportId);
2023-05-18 22:13:18 +02:00
2023-07-30 09:11:26 +02:00
if (!(await canViewReport(req.auth, report))) {
2023-05-18 22:13:18 +02:00
return unauthorized(res);
}
2023-07-30 09:11:26 +02:00
report.parameters = JSON.parse(report.parameters);
2023-07-30 09:11:26 +02:00
return ok(res, report);
2023-05-18 22:13:18 +02:00
}
if (req.method === 'POST') {
const { websiteId, type, name, description, parameters } = req.body;
2023-05-18 22:13:18 +02:00
2023-07-30 09:11:26 +02:00
const report = await getReportById(reportId);
2023-05-18 22:13:18 +02:00
2023-07-30 09:11:26 +02:00
if (!(await canUpdateReport(req.auth, report))) {
2023-05-18 22:13:18 +02:00
return unauthorized(res);
}
2023-07-30 07:03:34 +02:00
const result = await updateReport(reportId, {
websiteId,
userId,
type,
name,
description,
parameters: JSON.stringify(parameters),
} as any);
2023-05-18 22:13:18 +02:00
return ok(res, result);
2023-05-18 22:13:18 +02:00
}
2023-07-30 09:11:26 +02:00
if (req.method === 'DELETE') {
const report = await getReportById(reportId);
if (!(await canDeleteReport(req.auth, report))) {
return unauthorized(res);
}
await deleteReport(reportId);
return ok(res);
}
2023-05-18 22:13:18 +02:00
return methodNotAllowed(res);
};