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

94 lines
2.0 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;
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
const {
user: { id: userId },
} = req.auth;
const {
id: websiteId,
start_at,
end_at,
url,
referrer,
os,
browser,
device,
country,
} = req.query;
2022-10-12 22:11:44 +02:00
if (req.method === 'GET') {
if (!(await canViewWebsite(userId, websiteId))) {
return unauthorized(res);
}
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);
};