umami/pages/api/websites/[id]/eventdata.ts

55 lines
1.4 KiB
TypeScript
Raw Normal View History

import { WebsiteMetric, NextApiRequestQueryBody } from 'lib/types';
import { canViewWebsite } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
2022-11-15 22:21:14 +01:00
import { NextApiResponse } from 'next';
2022-11-19 03:49:58 +01:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getEventData } from 'queries';
2022-11-15 22:21:14 +01:00
export interface WebsiteEventDataRequestQuery {
id: string;
}
export interface WebsiteEventDataRequestBody {
start_at: string;
end_at: string;
event_name: string;
columns: { [key: string]: 'count' | 'max' | 'min' | 'avg' | 'sum' };
filters?: { [key: string]: any };
}
export default async (
req: NextApiRequestQueryBody<WebsiteEventDataRequestQuery, WebsiteEventDataRequestBody>,
res: NextApiResponse<WebsiteMetric>,
) => {
await useCors(req, res);
await useAuth(req, res);
const {
user: { id: userId },
} = req.auth;
const { id: websiteId } = req.query;
if (req.method === 'POST') {
if (canViewWebsite(userId, websiteId)) {
return unauthorized(res);
}
2022-11-19 03:49:58 +01:00
const { start_at, end_at, event_name: eventName, columns, filters } = req.body;
const startDate = new Date(+start_at);
const endDate = new Date(+end_at);
const events = await getEventData(websiteId, {
startDate,
endDate,
eventName,
columns,
filters,
});
return ok(res, events);
}
return methodNotAllowed(res);
};