1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
|
import { z } from 'zod';
import { checkAuth } from '@/lib/auth';
import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS } from '@/lib/constants';
import { getAllowedUnits, getMinimumUnit, maxDate, parseDateRange } from '@/lib/date';
import { fetchWebsite } from '@/lib/load';
import { filtersArrayToObject } from '@/lib/params';
import { badRequest, unauthorized } from '@/lib/response';
import type { QueryFilters } from '@/lib/types';
import { getWebsiteSegment } from '@/queries/prisma';
export async function parseRequest(
request: Request,
schema?: any,
options?: { skipAuth: boolean },
): Promise<any> {
const url = new URL(request.url);
let query = Object.fromEntries(url.searchParams);
let body = await getJsonBody(request);
let error: () => undefined | undefined;
let auth = null;
if (schema) {
const isGet = request.method === 'GET';
const result = schema.safeParse(isGet ? query : body);
if (!result.success) {
error = () => badRequest(z.treeifyError(result.error));
} else if (isGet) {
query = result.data;
} else {
body = result.data;
}
}
if (!options?.skipAuth && !error) {
auth = await checkAuth(request);
if (!auth) {
error = () => unauthorized();
}
}
return { url, query, body, auth, error };
}
export async function getJsonBody(request: Request) {
try {
return await request.clone().json();
} catch {
return undefined;
}
}
export function getRequestDateRange(query: Record<string, string>) {
const { startAt, endAt, unit, timezone } = query;
const startDate = new Date(+startAt);
const endDate = new Date(+endAt);
return {
startDate,
endDate,
timezone,
unit: getAllowedUnits(startDate, endDate).includes(unit)
? unit
: getMinimumUnit(startDate, endDate),
};
}
export function getRequestFilters(query: Record<string, any>) {
const result: Record<string, any> = {};
for (const key of Object.keys(FILTER_COLUMNS)) {
const value = query[key];
if (value !== undefined) {
result[key] = value;
}
}
return result;
}
export async function setWebsiteDate(websiteId: string, data: Record<string, any>) {
const website = await fetchWebsite(websiteId);
if (website?.resetAt) {
data.startDate = maxDate(data.startDate, new Date(website?.resetAt));
}
return data;
}
export async function getQueryFilters(
params: Record<string, any>,
websiteId?: string,
): Promise<QueryFilters> {
const dateRange = getRequestDateRange(params);
const filters = getRequestFilters(params);
if (websiteId) {
await setWebsiteDate(websiteId, dateRange);
if (params.segment) {
const segmentParams = (await getWebsiteSegment(websiteId, params.segment))
?.parameters as Record<string, any>;
Object.assign(filters, filtersArrayToObject(segmentParams.filters));
}
if (params.cohort) {
const cohortParams = (await getWebsiteSegment(websiteId, params.cohort))
?.parameters as Record<string, any>;
const { startDate, endDate } = parseDateRange(cohortParams.dateRange);
const cohortFilters = cohortParams.filters.map(({ name, ...props }) => ({
...props,
name: `cohort_${name}`,
}));
cohortFilters.push({
name: `cohort_${cohortParams.action.type}`,
operator: 'eq',
value: cohortParams.action.value,
});
Object.assign(filters, {
...filtersArrayToObject(cohortFilters),
cohort_startDate: startDate,
cohort_endDate: endDate,
});
}
}
return {
...dateRange,
...filters,
page: params?.page,
pageSize: params?.pageSize ? params?.pageSize || DEFAULT_PAGE_SIZE : undefined,
orderBy: params?.orderBy,
sortDescending: params?.sortDescending,
search: params?.search,
compare: params?.compare,
};
}
|