umami/src/pages/api/reports/insights.ts

97 lines
2.3 KiB
TypeScript
Raw Normal View History

import { canViewWebsite } from 'lib/auth';
2023-08-20 07:23:15 +02:00
import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody } from 'lib/types';
import { NextApiResponse } from 'next';
2023-08-20 07:23:15 +02:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getInsights } from 'queries';
2023-08-20 07:23:15 +02:00
import * as yup from 'yup';
export interface InsightsRequestBody {
websiteId: string;
dateRange: {
startDate: string;
endDate: string;
};
2023-08-24 01:24:14 +02:00
fields: { name: string; type: string; label: string }[];
2024-03-27 01:31:16 +01:00
filters: { name: string; type: string; operator: string; value: string }[];
2023-08-07 07:52:17 +02:00
groups: { name: string; type: string }[];
}
2023-08-20 07:23:15 +02:00
const schema = {
POST: yup.object().shape({
websiteId: yup.string().uuid().required(),
dateRange: yup
.object()
.shape({
startDate: yup.date().required(),
endDate: yup.date().required(),
})
.required(),
fields: yup
.array()
.of(
yup.object().shape({
name: yup.string().required(),
type: yup.string().required(),
2023-08-24 01:24:14 +02:00
label: yup.string().required(),
}),
)
.min(1)
.required(),
filters: yup.array().of(
yup.object().shape({
name: yup.string().required(),
type: yup.string().required(),
2024-03-27 01:31:16 +01:00
operator: yup.string().required(),
value: yup.string().required(),
}),
),
2023-08-20 07:23:15 +02:00
groups: yup.array().of(
yup.object().shape({
name: yup.string().required(),
type: yup.string().required(),
}),
),
}),
};
2023-12-02 01:02:50 +01:00
function convertFilters(filters: any[]) {
return filters.reduce((obj, filter) => {
obj[filter.name] = filter;
2023-08-11 18:05:56 +02:00
return obj;
}, {});
}
export default async (
req: NextApiRequestQueryBody<any, InsightsRequestBody>,
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);
2023-09-30 05:24:48 +02:00
await useValidate(schema, req, res);
2023-08-20 07:23:15 +02:00
if (req.method === 'POST') {
const {
websiteId,
dateRange: { startDate, endDate },
2023-08-08 08:02:38 +02:00
fields,
2023-08-07 07:52:17 +02:00
filters,
} = req.body;
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2023-08-08 08:02:38 +02:00
const data = await getInsights(websiteId, fields, {
2023-08-11 18:05:56 +02:00
...convertFilters(filters),
2023-08-07 07:52:17 +02:00
startDate: new Date(startDate),
endDate: new Date(endDate),
});
return ok(res, data);
}
return methodNotAllowed(res);
};