2022-07-12 23:14:36 +02:00
|
|
|
import { getWebsiteStats } from 'queries';
|
2020-10-09 00:02:48 +02:00
|
|
|
import { methodNotAllowed, ok, unauthorized } from 'lib/response';
|
|
|
|
import { allowQuery } from 'lib/auth';
|
2022-04-04 09:33:20 +02:00
|
|
|
import { useCors } from 'lib/middleware';
|
2020-10-09 00:02:48 +02:00
|
|
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
if (req.method === 'GET') {
|
2022-04-04 09:33:20 +02:00
|
|
|
await useCors(req, res);
|
|
|
|
|
2020-10-09 00:02:48 +02:00
|
|
|
if (!(await allowQuery(req))) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2022-04-10 12:51:43 +02:00
|
|
|
const { id, start_at, end_at, url, referrer, os, browser, device, country } = req.query;
|
2020-10-09 00:02:48 +02:00
|
|
|
|
|
|
|
const websiteId = +id;
|
|
|
|
const startDate = new Date(+start_at);
|
|
|
|
const endDate = new Date(+end_at);
|
|
|
|
|
2021-08-13 01:01:51 +02:00
|
|
|
const distance = end_at - start_at;
|
|
|
|
const prevStartDate = new Date(+start_at - distance);
|
|
|
|
const prevEndDate = new Date(+end_at - distance);
|
|
|
|
|
2022-04-10 12:51:43 +02:00
|
|
|
const metrics = await getWebsiteStats(websiteId, startDate, endDate, {
|
|
|
|
url,
|
|
|
|
referrer,
|
|
|
|
os,
|
|
|
|
browser,
|
|
|
|
device,
|
|
|
|
country,
|
|
|
|
});
|
2022-03-20 22:10:41 +01:00
|
|
|
const prevPeriod = await getWebsiteStats(websiteId, prevStartDate, prevEndDate, {
|
|
|
|
url,
|
|
|
|
referrer,
|
2022-04-10 12:51:43 +02:00
|
|
|
os,
|
|
|
|
browser,
|
|
|
|
device,
|
|
|
|
country,
|
2022-03-20 22:10:41 +01:00
|
|
|
});
|
2020-10-09 00:02:48 +02:00
|
|
|
|
|
|
|
const stats = Object.keys(metrics[0]).reduce((obj, key) => {
|
2021-08-13 01:01:51 +02:00
|
|
|
obj[key] = {
|
|
|
|
value: Number(metrics[0][key]) || 0,
|
2022-07-21 10:35:14 +02:00
|
|
|
change: Number(metrics[0][key]) - Number(prevPeriod[0][key]) || 0,
|
2021-08-13 01:01:51 +02:00
|
|
|
};
|
2020-10-09 00:02:48 +02:00
|
|
|
return obj;
|
|
|
|
}, {});
|
|
|
|
|
|
|
|
return ok(res, stats);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|