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

74 lines
1.6 KiB
TypeScript
Raw Normal View History

import { canUpdateReport, canViewReport } 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';
import { getReportById, updateReport } 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);
if (req.method === 'GET') {
const { id: reportId } = req.query;
2023-05-18 22:13:18 +02:00
const data = await getReportById(reportId);
2023-05-18 22:13:18 +02:00
if (!(await canViewReport(req.auth, data))) {
2023-05-18 22:13:18 +02:00
return unauthorized(res);
}
data.parameters = JSON.parse(data.parameters);
2023-05-18 22:13:18 +02:00
return ok(res, data);
}
if (req.method === 'POST') {
const { id: reportId } = req.query;
2023-05-31 01:49:22 +02:00
const {
user: { id: userId },
} = req.auth;
const { websiteId, type, name, description, parameters } = req.body;
2023-05-18 22:13:18 +02:00
const data = await getReportById(reportId);
2023-05-18 22:13:18 +02:00
if (!(await canUpdateReport(req.auth, data))) {
2023-05-18 22:13:18 +02:00
return unauthorized(res);
}
const result = await updateReport(
2023-05-18 22:13:18 +02:00
{
websiteId,
2023-05-31 01:49:22 +02:00
userId,
type,
name,
description,
parameters: JSON.stringify(parameters),
} as any,
2023-05-18 22:13:18 +02:00
{
id: reportId,
2023-05-18 22:13:18 +02:00
},
);
return ok(res, result);
2023-05-18 22:13:18 +02:00
}
return methodNotAllowed(res);
};