umami/pages/api/reports/retention.ts

57 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-08-04 20:10:03 +00:00
import { canViewWebsite } from 'lib/auth';
2023-08-20 05:23:15 +00:00
import { useAuth, useCors, useValidate } from 'lib/middleware';
2023-08-04 20:10:03 +00:00
import { NextApiRequestQueryBody } from 'lib/types';
import { NextApiResponse } from 'next';
2023-08-20 05:23:15 +00:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
2023-08-04 20:10:03 +00:00
import { getRetention } from 'queries';
2023-08-20 05:23:15 +00:00
import * as yup from 'yup';
2023-08-04 20:10:03 +00:00
export interface RetentionRequestBody {
websiteId: string;
2023-08-20 05:23:15 +00:00
dateRange: { startDate: string; endDate: string };
2023-08-04 20:10:03 +00:00
}
2023-08-20 05:23:15 +00: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(),
}),
};
2023-08-04 20:10:03 +00:00
export default async (
req: NextApiRequestQueryBody<any, RetentionRequestBody>,
2023-08-20 05:23:15 +00:00
res: NextApiResponse,
2023-08-04 20:10:03 +00:00
) => {
await useCors(req, res);
await useAuth(req, res);
2023-08-20 05:23:15 +00:00
req.yup = schema;
await useValidate(req, res);
2023-08-04 20:10:03 +00:00
if (req.method === 'POST') {
const {
websiteId,
dateRange: { startDate, endDate },
} = req.body;
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
const data = await getRetention(websiteId, {
startDate: new Date(startDate),
endDate: new Date(endDate),
});
return ok(res, data);
}
return methodNotAllowed(res);
};