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

51 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-08-08 22:29:59 +00:00
import { NextApiRequestQueryBody } from 'lib/types';
import { canViewWebsite } from 'lib/auth';
2023-08-20 05:23:15 +00:00
import { useAuth, useCors, useValidate } from 'lib/middleware';
2023-08-08 22:29:59 +00:00
import { NextApiResponse } from 'next';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
2023-08-09 22:06:19 +00:00
import { EVENT_COLUMNS, FILTER_COLUMNS, SESSION_COLUMNS } from 'lib/constants';
2023-08-08 22:29:59 +00:00
import { getValues } from 'queries';
2023-09-20 21:36:18 +00:00
export interface ValuesRequestQuery {
2023-08-08 22:29:59 +00:00
id: string;
}
2023-08-20 05:23:15 +00:00
import * as yup from 'yup';
const schema = {
GET: yup.object().shape({
id: yup.string().uuid().required(),
}),
};
2023-09-20 21:36:18 +00:00
export default async (req: NextApiRequestQueryBody<ValuesRequestQuery>, res: NextApiResponse) => {
2023-08-08 22:29:59 +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-08 22:29:59 +00:00
const { id: websiteId, type } = req.query;
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);
}
2023-08-09 22:06:19 +00:00
const values = await getValues(websiteId, FILTER_COLUMNS[type as string]);
2023-08-08 22:29:59 +00:00
return ok(
res,
values
.map(({ value }) => value)
.filter(n => n)
.sort(),
);
}
return methodNotAllowed(res);
};