|
1
|
import { DAL, FindConfig, InferRepositoryReturnType } from "@medusajs/types" |
|
2
|
import { deduplicate, isObject } from "../common" |
|
3
|
|
|
4
|
import { SoftDeletableFilterKey } from "../dal/mikro-orm/mikro-orm-soft-deletable-filter" |
|
5
|
|
|
6
|
export function buildQuery<const T = any>( |
|
7
|
filters: Record<string, any> = {}, |
|
8
|
config: FindConfig<InferRepositoryReturnType<T>> & { |
|
9
|
primaryKeyFields?: string | string[] |
|
10
|
} = {} |
|
11
|
): Required<DAL.FindOptions<T>> { |
|
12
|
const where = {} as DAL.FilterQuery<T> |
|
13
|
buildWhere(filters, where) |
|
14
|
|
|
15
|
delete config.primaryKeyFields |
|
16
|
|
|
17
|
const findOptions: DAL.FindOptions<T>["options"] = { |
|
18
|
populate: deduplicate(config.relations ?? []), |
|
19
|
fields: config.select as string[], |
|
20
|
limit: |
|
21
|
Number.isSafeInteger(config.take) && config.take != null |
|
22
|
? config.take |
|
23
|
: undefined, |
|
24
|
offset: |
|
25
|
Number.isSafeInteger(config.skip) && config.skip != null |
|
26
|
? config.skip |
|
27
|
: undefined, |
|
28
|
__internal: config.__internal, |
|
29
|
} |
|
30
|
|
|
31
|
if (config.order) { |
|
32
|
findOptions.orderBy = config.order as Required< |
|
33
|
DAL.FindOptions<T> |
|
34
|
>["options"]["orderBy"] |
|
35
|
} |
|
36
|
|
|
37
|
if (config.withDeleted) { |
|
38
|
findOptions.filters ??= {} |
|
39
|
findOptions.filters[SoftDeletableFilterKey] = { |
|
40
|
withDeleted: true, |
|
41
|
} |
|
42
|
} |
|
43
|
|
|
44
|
if (config.filters) { |
|
45
|
findOptions.filters ??= {} |
|
46
|
|
|
47
|
for (const [key, value] of Object.entries(config.filters)) { |
|
48
|
findOptions.filters[key] = value |
|
49
|
} |
|
50
|
} |
|
51
|
|
|
52
|
if (config.options) { |
|
53
|
Object.assign(findOptions, config.options) |
|
54
|
} |
|
55
|
|
|
56
|
return { where, options: findOptions } as Required<DAL.FindOptions<T>> |
|
57
|
} |
|
58
|
|
|
59
|
function buildWhere(filters: Record<string, any> = {}, where = {}) { |
|
60
|
for (let [prop, value] of Object.entries(filters)) { |
|
61
|
if (["$or", "$and"].includes(prop)) { |
|
62
|
if (!Array.isArray(value)) { |
|
63
|
throw new Error(`Expected array for ${prop} but got ${value}`) |
|
64
|
} |
|
65
|
|
|
66
|
where[prop] = value.map((val) => { |
|
67
|
const deepWhere = {} |
|
68
|
buildWhere(val, deepWhere) |
|
69
|
return deepWhere |
|
70
|
}) |
|
71
|
continue |
|
72
|
} |
|
73
|
|
|
74
|
if (Array.isArray(value)) { |
|
75
|
where[prop] = deduplicate(value) |
|
76
|
continue |
|
77
|
} |
|
78
|
|
|
79
|
if (isObject(value)) { |
|
80
|
where[prop] = {} |
|
81
|
buildWhere(value, where[prop]) |
|
82
|
continue |
|
83
|
} |
|
84
|
|
|
85
|
where[prop] = value |
|
86
|
} |
|
87
|
} |