-
-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathbuild-query.ts
More file actions
86 lines (71 loc) · 2.15 KB
/
Copy pathbuild-query.ts
File metadata and controls
86 lines (71 loc) · 2.15 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
import { DAL, FindConfig, InferRepositoryReturnType } from "@medusajs/types"
import { deduplicate, isObject } from "../common"
import { SoftDeletableFilterKey } from "../dal/mikro-orm/mikro-orm-soft-deletable-filter"
export function buildQuery<const T = any>(
filters: Record<string, any> = {},
config: FindConfig<InferRepositoryReturnType<T>> & {
primaryKeyFields?: string | string[]
} = {}
): Required<DAL.FindOptions<T>> {
const where = {} as DAL.FilterQuery<T>
buildWhere(filters, where)
delete config.primaryKeyFields
const findOptions: DAL.FindOptions<T>["options"] = {
populate: deduplicate(config.relations ?? []),
fields: config.select as string[],
limit:
Number.isSafeInteger(config.take) && config.take != null
? config.take
: undefined,
offset:
Number.isSafeInteger(config.skip) && config.skip != null
? config.skip
: undefined,
}
if (config.order) {
findOptions.orderBy = config.order as Required<
DAL.FindOptions<T>
>["options"]["orderBy"]
}
if (config.withDeleted) {
findOptions.filters ??= {}
findOptions.filters[SoftDeletableFilterKey] = {
withDeleted: true,
}
}
if (config.filters) {
findOptions.filters ??= {}
for (const [key, value] of Object.entries(config.filters)) {
findOptions.filters[key] = value
}
}
if (config.options) {
Object.assign(findOptions, config.options)
}
return { where, options: findOptions } as Required<DAL.FindOptions<T>>
}
function buildWhere(filters: Record<string, any> = {}, where = {}) {
for (let [prop, value] of Object.entries(filters)) {
if (["$or", "$and"].includes(prop)) {
if (!Array.isArray(value)) {
throw new Error(`Expected array for ${prop} but got ${value}`)
}
where[prop] = value.map((val) => {
const deepWhere = {}
buildWhere(val, deepWhere)
return deepWhere
})
continue
}
if (Array.isArray(value)) {
where[prop] = deduplicate(value)
continue
}
if (isObject(value)) {
where[prop] = {}
buildWhere(value, where[prop])
continue
}
where[prop] = value
}
}