2023-07-23 22:18:01 +02:00
|
|
|
import { canViewWebsite } from 'lib/auth';
|
|
|
|
import { useCors, useAuth } from 'lib/middleware';
|
|
|
|
import { NextApiRequestQueryBody } from 'lib/types';
|
|
|
|
import { NextApiResponse } from 'next';
|
|
|
|
import { ok, methodNotAllowed, unauthorized } from 'next-basics';
|
|
|
|
import { getInsights } from 'queries';
|
|
|
|
|
|
|
|
export interface InsightsRequestBody {
|
|
|
|
websiteId: string;
|
|
|
|
dateRange: {
|
|
|
|
startDate: string;
|
|
|
|
endDate: string;
|
|
|
|
};
|
2023-08-04 09:51:52 +02:00
|
|
|
fields: { name: string; type: string; value: string }[];
|
2023-07-23 22:18:01 +02:00
|
|
|
filters: string[];
|
|
|
|
groups: string[];
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
|
|
|
req: NextApiRequestQueryBody<any, InsightsRequestBody>,
|
|
|
|
res: NextApiResponse,
|
|
|
|
) => {
|
|
|
|
await useCors(req, res);
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
|
|
|
if (req.method === 'POST') {
|
|
|
|
const {
|
|
|
|
websiteId,
|
|
|
|
dateRange: { startDate, endDate },
|
|
|
|
fields,
|
|
|
|
filters,
|
|
|
|
groups,
|
|
|
|
} = req.body;
|
|
|
|
|
|
|
|
if (!(await canViewWebsite(req.auth, websiteId))) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2023-08-05 18:09:54 +02:00
|
|
|
const data = await getInsights(
|
|
|
|
websiteId,
|
|
|
|
{
|
|
|
|
...filters,
|
|
|
|
startDate: new Date(startDate),
|
|
|
|
endDate: new Date(endDate),
|
|
|
|
},
|
2023-07-23 22:18:01 +02:00
|
|
|
groups,
|
2023-08-05 18:09:54 +02:00
|
|
|
);
|
2023-07-23 22:18:01 +02:00
|
|
|
|
|
|
|
return ok(res, data);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|