-
Notifications
You must be signed in to change notification settings - Fork 673
Expand file tree
/
Copy pathGraphQLInputMapper.ts
More file actions
63 lines (53 loc) · 2.23 KB
/
Copy pathGraphQLInputMapper.ts
File metadata and controls
63 lines (53 loc) · 2.23 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
import { immutableGet } from "@webiny/utils/dotProp/index.js";
import type { FilterDTO } from "~/components/AdvancedSearch/domain/index.js";
interface NestedObject {
[key: string]: string | boolean | NestedObject;
}
export class GraphQLInputMapper {
static toGraphQL(configuration: FilterDTO) {
return {
[configuration.operation]: configuration.groups.map(group => {
return {
[group.operation]: group.filters.map(filter => {
const { field, condition, value } = filter;
const keys = field.trim().split(".");
keys.shift();
if (keys.length === 0) {
return this.createNestedObject(
this.createKeys(field, condition),
this.convertToBooleanOrString(value)
);
}
try {
const values = JSON.parse(value);
return this.createNestedObject(
this.createKeys(field, condition),
this.convertToBooleanOrString(immutableGet(values, keys.join(".")))
);
} catch {
return this.createNestedObject(
this.createKeys(field, condition),
this.convertToBooleanOrString(value)
);
}
})
};
})
};
}
private static convertToBooleanOrString(value: string | boolean): string | boolean {
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
return value ?? "";
}
private static createKeys(field: string, condition: string): string[] {
return `${field}${condition}`.trim().split(".");
}
private static createNestedObject(keys: string[], value: string | boolean): NestedObject {
return keys.reduceRight((acc, key) => ({ [key]: acc }), value as unknown as NestedObject);
}
}