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

107 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-12-07 03:36:41 +01:00
import { WebsiteStats } from 'lib/types';
import { NextApiRequestQueryBody } from 'lib/types';
import { canViewWebsite } from 'lib/auth';
2022-11-19 03:49:58 +01:00
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 { getWebsiteStats } from 'queries';
2022-11-18 07:46:05 +01:00
export interface WebsiteStatsRequestQuery {
2022-11-15 22:21:14 +01:00
id: string;
type: string;
2022-12-27 02:36:48 +01:00
startAt: number;
endAt: number;
2022-11-15 22:21:14 +01:00
url: string;
referrer: string;
2023-03-01 19:53:57 +01:00
pageTitle: string;
2022-11-15 22:21:14 +01:00
os: string;
browser: string;
device: string;
country: string;
subdivision1: string;
subdivision2: string;
city: string;
2022-11-15 22:21:14 +01:00
}
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
const {
id: websiteId,
startAt,
endAt,
url,
referrer,
2023-03-01 19:53:57 +01:00
pageTitle,
os,
browser,
device,
country,
subdivision1,
subdivision2,
city,
} = req.query;
2022-10-12 22:11:44 +02:00
if (req.method === 'GET') {
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2022-12-27 02:36:48 +01:00
const startDate = new Date(+startAt);
const endDate = new Date(+endAt);
2022-12-27 02:36:48 +01:00
const distance = endAt - startAt;
const prevStartDate = new Date(+startAt - distance);
const prevEndDate = new Date(+endAt - 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,
2023-03-01 19:53:57 +01:00
pageTitle,
2022-09-24 07:43:51 +02:00
os,
browser,
device,
country,
subdivision1,
subdivision2,
city,
2022-09-24 07:43:51 +02:00
},
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,
2023-03-01 19:53:57 +01:00
pageTitle,
2022-09-24 07:43:51 +02:00
os,
browser,
device,
country,
subdivision1,
subdivision2,
city,
2022-09-24 07:43:51 +02:00
},
});
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);
};