2023-07-26 06:59:08 +00:00
|
|
|
import { NextApiRequest } from 'next';
|
|
|
|
|
import { getAllowedUnits, getMinimumUnit } from './date';
|
|
|
|
|
import { getWebsiteDateRange } from '../queries';
|
2024-04-01 17:10:56 +00:00
|
|
|
import { FILTER_COLUMNS, OPERATORS, OPERATOR_PREFIXES } from 'lib/constants';
|
2023-07-26 06:59:08 +00:00
|
|
|
|
|
|
|
|
export async function parseDateRangeQuery(req: NextApiRequest) {
|
2024-02-01 06:08:48 +00:00
|
|
|
const { websiteId, startAt, endAt, unit } = req.query;
|
2023-07-26 06:59:08 +00:00
|
|
|
|
|
|
|
|
// All-time
|
|
|
|
|
if (+startAt === 0 && +endAt === 1) {
|
2023-07-26 20:42:55 +00:00
|
|
|
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 06:59:08 +00:00
|
|
|
|
|
|
|
|
return {
|
2023-07-26 20:42:55 +00:00
|
|
|
startDate,
|
|
|
|
|
endDate,
|
|
|
|
|
unit: getMinimumUnit(startDate, endDate),
|
2023-07-26 06:59:08 +00:00
|
|
|
};
|
2023-04-02 00:38:35 +00:00
|
|
|
}
|
|
|
|
|
|
2023-07-26 06:59:08 +00:00
|
|
|
const startDate = new Date(+startAt);
|
|
|
|
|
const endDate = new Date(+endAt);
|
|
|
|
|
const minUnit = getMinimumUnit(startDate, endDate);
|
2023-04-02 00:38:35 +00:00
|
|
|
|
2023-07-26 06:59:08 +00:00
|
|
|
return {
|
|
|
|
|
startDate,
|
|
|
|
|
endDate,
|
2023-07-26 16:55:54 +00:00
|
|
|
unit: (getAllowedUnits(startDate, endDate).includes(unit as string) ? unit : minUnit) as string,
|
2023-07-26 06:59:08 +00:00
|
|
|
};
|
2023-04-02 00:38:35 +00:00
|
|
|
}
|
2024-03-27 09:17:55 +00:00
|
|
|
|
|
|
|
|
export function getQueryFilters(req: NextApiRequest) {
|
|
|
|
|
return Object.keys(FILTER_COLUMNS).reduce((obj, key) => {
|
|
|
|
|
const value = req.query[key];
|
|
|
|
|
|
|
|
|
|
if (value) {
|
|
|
|
|
obj[key] = value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (typeof value === 'string') {
|
|
|
|
|
const [, prefix, paramValue] = value.match(/^(!~|!|~)?(.*)$/);
|
|
|
|
|
|
|
|
|
|
if (prefix && paramValue) {
|
|
|
|
|
obj[key] = {
|
|
|
|
|
name: key,
|
|
|
|
|
column: FILTER_COLUMNS[key],
|
2024-04-01 17:10:56 +00:00
|
|
|
operator: OPERATOR_PREFIXES[prefix] || OPERATORS.equals,
|
2024-03-27 09:17:55 +00:00
|
|
|
value: paramValue,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return obj;
|
|
|
|
|
}, {});
|
|
|
|
|
}
|