-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleFilter.ts
More file actions
52 lines (46 loc) · 1.27 KB
/
Copy pathSimpleFilter.ts
File metadata and controls
52 lines (46 loc) · 1.27 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
/**
* Simple Key-Value Filtering
*
* The most basic approach: direct field-to-value mapping.
* Useful for exact matches and basic comparisons.
*
* URL: ?userId=42&status=active&name=John
*/
export interface SimpleFilters {
[key: string]: string | number | boolean | undefined
}
export function buildSimpleFilter(filters: SimpleFilters): URLSearchParams {
const params = new URLSearchParams()
for (const [k, v] of Object.entries(filters)) {
if (v !== undefined) {
params.set(k, String(v))
}
}
return params
}
// Frontend usage example
const filters = {
userId: 42,
status: "active",
archived: false,
name: undefined, // Dropped
}
const url = `/api/users?${buildSimpleFilter(filters)}`
// => /api/users?userId=42&status=active&archived=false
/**
* Backend parsing (Node.js / Express)
*/
export function parseSimpleFilter(params: URLSearchParams): Record<string, any> {
const result: Record<string, any> = {}
for (const [key, value] of params) {
result[key] = value // Still a string; may need type coercion
}
return result
}
// Database query example
function applySimpleFilters(filters: Record<string, any>, query: any) {
for (const [field, value] of Object.entries(filters)) {
query = query.where(field, "=", value)
}
return query
}