-
-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathfilters.ts
More file actions
103 lines (82 loc) · 2.66 KB
/
filters.ts
File metadata and controls
103 lines (82 loc) · 2.66 KB
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
import type { PropertyFilterProps } from 'components';
export const tokensToSearchParams = <RequestParamsKeys extends string>(
tokens: PropertyFilterProps.Query['tokens'],
onlyActive?: boolean,
) => {
const params = new URLSearchParams();
tokens.forEach((token) => {
if (token.propertyKey) {
params.append(token.propertyKey as RequestParamsKeys, token.value);
}
});
if (onlyActive) {
params.append('only_active', 'true');
}
return params;
};
export type RequestParam = string | { min: number } | { max: number };
const convertTokenValueToRequestParam = (token: PropertyFilterProps.Query['tokens'][number]): RequestParam => {
const { value, operator } = token;
if (operator === '>=') {
return { min: Number(value) };
}
if (operator === '<=') {
return { max: Number(value) };
}
return value;
};
export const tokensToRequestParams = <RequestParamsKeys extends string>({
tokens,
arrayFieldKeys,
}: {
tokens: PropertyFilterProps.Query['tokens'];
arrayFieldKeys?: RequestParamsKeys[];
}) => {
return tokens.reduce<Record<RequestParamsKeys, RequestParam | string[]>>(
(acc, token) => {
const propertyKey = token.propertyKey as RequestParamsKeys;
if (!propertyKey) {
return acc;
}
const convertedValue = convertTokenValueToRequestParam(token);
if (arrayFieldKeys?.includes(propertyKey)) {
if (Array.isArray(acc[propertyKey])) {
acc[propertyKey].push(convertedValue as string);
} else {
acc[propertyKey] = [convertedValue as string];
}
return acc;
}
acc[propertyKey] = convertedValue;
return acc;
},
{} as Record<RequestParamsKeys, RequestParam>,
);
};
export const EMPTY_QUERY: PropertyFilterProps.Query = {
tokens: [],
operation: 'and',
};
export const requestParamsToTokens = <RequestParamsKeys extends string>({
searchParams,
filterKeys,
}: {
searchParams: URLSearchParams;
filterKeys: Record<string, RequestParamsKeys>;
}): PropertyFilterProps.Query => {
const tokens = [];
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
for (const [paramKey, paramValue] of searchParams.entries()) {
if (Object.values(filterKeys).includes(paramKey)) {
tokens.push({ propertyKey: paramKey, operator: '=', value: paramValue });
}
}
if (!tokens.length) {
return EMPTY_QUERY;
}
return {
...EMPTY_QUERY,
tokens,
};
};