umami/src/pages/api/websites/[websiteId]/values.ts

71 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-08-09 00:29:59 +02:00
import { NextApiRequestQueryBody } from 'lib/types';
import { canViewWebsite } from 'lib/auth';
2023-08-20 07:23:15 +02:00
import { useAuth, useCors, useValidate } from 'lib/middleware';
2023-08-09 00:29:59 +02:00
import { NextApiResponse } from 'next';
2024-03-27 01:31:16 +01:00
import {
badRequest,
methodNotAllowed,
ok,
safeDecodeURIComponent,
unauthorized,
} from 'next-basics';
2023-08-10 00:06:19 +02:00
import { EVENT_COLUMNS, FILTER_COLUMNS, SESSION_COLUMNS } from 'lib/constants';
2023-08-09 00:29:59 +02:00
import { getValues } from 'queries';
2023-10-13 18:31:53 +02:00
import { parseDateRangeQuery } from 'lib/query';
2024-03-27 01:31:16 +01:00
import * as yup from 'yup';
2023-08-09 00:29:59 +02:00
2023-09-20 23:36:18 +02:00
export interface ValuesRequestQuery {
2024-02-01 07:08:48 +01:00
websiteId: string;
2024-03-27 01:31:16 +01:00
type: string;
2023-10-13 18:31:53 +02:00
startAt: number;
endAt: number;
2024-03-27 01:31:16 +01:00
search?: string;
2023-08-09 00:29:59 +02:00
}
2023-08-20 07:23:15 +02:00
const schema = {
GET: yup.object().shape({
2024-02-01 07:08:48 +01:00
websiteId: yup.string().uuid().required(),
2024-03-27 01:31:16 +01:00
type: yup.string().required(),
2023-10-13 18:31:53 +02:00
startAt: yup.number().required(),
endAt: yup.number().required(),
2024-03-27 01:31:16 +01:00
search: yup.string(),
2023-08-20 07:23:15 +02:00
}),
};
2023-09-20 23:36:18 +02:00
export default async (req: NextApiRequestQueryBody<ValuesRequestQuery>, res: NextApiResponse) => {
2023-08-09 00:29:59 +02:00
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
2024-03-27 01:31:16 +01:00
const { websiteId, type, search } = req.query;
2023-10-13 18:31:53 +02:00
const { startDate, endDate } = await parseDateRangeQuery(req);
2023-08-09 00:29:59 +02:00
if (req.method === 'GET') {
if (!SESSION_COLUMNS.includes(type as string) && !EVENT_COLUMNS.includes(type as string)) {
return badRequest(res);
}
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2024-03-27 01:31:16 +01:00
const values = await getValues(
websiteId,
FILTER_COLUMNS[type as string],
startDate,
endDate,
search,
);
2023-08-09 00:29:59 +02:00
return ok(
res,
values
2024-03-27 01:31:16 +01:00
.map(({ value }) => safeDecodeURIComponent(value))
2023-08-09 00:29:59 +02:00
.filter(n => n)
.sort(),
);
}
return methodNotAllowed(res);
};