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

84 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-08-10 20:26:33 +00:00
import { uuid } from 'lib/crypto';
2023-08-20 05:23:15 +00:00
import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, SearchFilter } from 'lib/types';
2023-09-22 07:59:00 +00:00
import { pageInfo } from 'lib/schema';
2023-05-18 20:13:18 +00:00
import { NextApiResponse } from 'next';
2023-08-20 05:23:15 +00:00
import { methodNotAllowed, ok } from 'next-basics';
import { createReport, getReportsByUserId } from 'queries';
import * as yup from 'yup';
2023-08-10 20:26:33 +00:00
export interface ReportsRequestQuery extends SearchFilter {}
2023-05-18 20:13:18 +00:00
export interface ReportRequestBody {
2023-05-18 20:13:18 +00:00
websiteId: string;
name: string;
type: string;
description: string;
parameters: {
2023-08-20 05:23:15 +00:00
[key: string]: any;
};
2023-05-18 20:13:18 +00:00
}
2023-08-20 05:23:15 +00:00
const schema = {
GET: yup.object().shape({
2023-09-22 07:59:00 +00:00
...pageInfo,
2023-08-20 05:23:15 +00:00
}),
POST: yup.object().shape({
websiteId: yup.string().uuid().required(),
name: yup.string().max(200).required(),
type: yup
.string()
.matches(/funnel|insights|retention/i)
.required(),
description: yup.string().max(500),
parameters: yup
.object()
.test('len', 'Must not exceed 6000 characters.', val => JSON.stringify(val).length < 6000),
}),
};
2023-05-18 20:13:18 +00:00
export default async (
req: NextApiRequestQueryBody<any, ReportRequestBody>,
2023-05-18 20:13:18 +00:00
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);
2023-08-20 05:23:15 +00:00
req.yup = schema;
await useValidate(req, res);
2023-05-18 20:13:18 +00:00
const {
user: { id: userId },
} = req.auth;
if (req.method === 'GET') {
const { page, query } = req.query;
2023-08-10 20:26:33 +00:00
2023-08-14 05:21:49 +00:00
const data = await getReportsByUserId(userId, {
2023-08-10 20:26:33 +00:00
page,
query,
2023-08-17 23:39:59 +00:00
includeTeams: true,
2023-08-10 20:26:33 +00:00
});
2023-05-18 20:13:18 +00:00
return ok(res, data);
}
if (req.method === 'POST') {
const { websiteId, type, name, description, parameters } = req.body;
const result = await createReport({
2023-05-18 20:13:18 +00:00
id: uuid(),
userId,
websiteId,
type,
name,
description,
parameters: JSON.stringify(parameters),
} as any);
return ok(res, result);
2023-05-18 20:13:18 +00:00
}
return methodNotAllowed(res);
};