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

92 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-10-11 02:01:48 +02:00
import { getWebsiteStats } from 'queries';
2022-08-29 05:20:54 +02:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth';
2022-10-12 22:11:44 +02:00
import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
2022-11-15 22:21:14 +01:00
import { WebsiteStats } from 'interface/api/models';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
2022-11-18 07:46:05 +01:00
export interface WebsiteStatsRequestQuery {
2022-11-15 22:21:14 +01:00
id: string;
type: string;
start_at: number;
end_at: number;
url: string;
referrer: string;
os: string;
browser: string;
device: string;
country: string;
}
export default async (
2022-11-18 07:46:05 +01:00
req: NextApiRequestQueryBody<WebsiteStatsRequestQuery>,
2022-11-15 22:21:14 +01:00
res: NextApiResponse<WebsiteStats>,
) => {
2022-10-12 22:11:44 +02:00
await useCors(req, res);
await useAuth(req, res);
2022-04-04 09:33:20 +02:00
2022-10-12 22:11:44 +02:00
if (req.method === 'GET') {
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}
2022-10-12 04:37:38 +02:00
const {
id: websiteId,
start_at,
end_at,
url,
referrer,
os,
browser,
device,
country,
} = req.query;
const startDate = new Date(+start_at);
const endDate = new Date(+end_at);
const distance = end_at - start_at;
const prevStartDate = new Date(+start_at - distance);
const prevEndDate = new Date(+end_at - distance);
2022-10-11 02:01:48 +02:00
const metrics = await getWebsiteStats(websiteId, {
2022-11-18 07:27:33 +01:00
startDate,
endDate,
2022-09-24 07:43:51 +02:00
filters: {
url,
referrer,
os,
browser,
device,
country,
},
2022-04-10 12:51:43 +02:00
});
2022-10-11 02:01:48 +02:00
const prevPeriod = await getWebsiteStats(websiteId, {
2022-11-18 07:27:33 +01:00
startDate: prevStartDate,
endDate: prevEndDate,
2022-09-24 07:43:51 +02:00
filters: {
url,
referrer,
os,
browser,
device,
country,
},
});
const stats = Object.keys(metrics[0]).reduce((obj, key) => {
obj[key] = {
value: Number(metrics[0][key]) || 0,
change: Number(metrics[0][key]) - Number(prevPeriod[0][key]) || 0,
};
return obj;
}, {});
return ok(res, stats);
}
return methodNotAllowed(res);
};