umami/src/lib/request.ts

45 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-07-26 08:59:08 +02:00
import { NextApiRequest } from 'next';
import { getAllowedUnits, getMinimumUnit } from './date';
import { getWebsiteDateRange } from '../queries';
2024-04-03 02:06:06 +02:00
import { FILTER_COLUMNS } from 'lib/constants';
2023-07-26 08:59:08 +02:00
2024-04-03 02:06:06 +02:00
export async function getRequestDateRange(req: NextApiRequest) {
2024-02-01 07:08:48 +01:00
const { websiteId, startAt, endAt, unit } = req.query;
2023-07-26 08:59:08 +02:00
// All-time
if (+startAt === 0 && +endAt === 1) {
const result = await getWebsiteDateRange(websiteId as string);
const { min, max } = result[0];
const startDate = new Date(min);
const endDate = new Date(max);
2023-07-26 08:59:08 +02:00
return {
startDate,
endDate,
unit: getMinimumUnit(startDate, endDate),
2023-07-26 08:59:08 +02:00
};
2023-04-02 02:38:35 +02:00
}
2023-07-26 08:59:08 +02:00
const startDate = new Date(+startAt);
const endDate = new Date(+endAt);
const minUnit = getMinimumUnit(startDate, endDate);
2023-04-02 02:38:35 +02:00
2023-07-26 08:59:08 +02:00
return {
startDate,
endDate,
2023-07-26 18:55:54 +02:00
unit: (getAllowedUnits(startDate, endDate).includes(unit as string) ? unit : minUnit) as string,
2023-07-26 08:59:08 +02:00
};
2023-04-02 02:38:35 +02:00
}
2024-04-03 02:06:06 +02:00
export function getRequestFilters(req: NextApiRequest) {
return Object.keys(FILTER_COLUMNS).reduce((obj, key) => {
const value = req.query[key];
2024-04-03 02:06:06 +02:00
if (value !== undefined) {
obj[key] = value;
}
return obj;
}, {});
}