-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathsanitizeWhereQuery.ts
More file actions
69 lines (58 loc) · 1.71 KB
/
sanitizeWhereQuery.ts
File metadata and controls
69 lines (58 loc) · 1.71 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
import type { FlattenedField } from '../fields/config/types.js'
import type { Payload, Where } from '../types/index.js'
/**
* Currently used only for virtual fields linked with relationships
*/
export const sanitizeWhereQuery = ({
fields,
payload,
where,
}: {
fields: FlattenedField[]
payload: Payload
where: Where
}) => {
for (const key in where) {
const value = where[key]
if (['and', 'or'].includes(key.toLowerCase()) && Array.isArray(value)) {
for (const where of value) {
sanitizeWhereQuery({ fields, payload, where })
}
continue
}
if (key.toLowerCase() === 'not' && typeof value === 'object' && !Array.isArray(value)) {
sanitizeWhereQuery({ fields, payload, where: value as Where })
continue
}
const paths = key.split('.')
let pathHasChanged = false
let currentFields = fields
for (let i = 0; i < paths.length; i++) {
const path = paths[i]!
const field = currentFields.find((each) => each.name === path)
if (!field) {
break
}
if ('virtual' in field && field.virtual && typeof field.virtual === 'string') {
paths[i] = field.virtual
pathHasChanged = true
}
if ('flattenedFields' in field) {
currentFields = field.flattenedFields
}
if (
(field.type === 'relationship' || field.type === 'upload') &&
typeof field.relationTo === 'string'
) {
const relatedCollection = payload.collections[field.relationTo]
if (relatedCollection) {
currentFields = relatedCollection.config.flattenedFields
}
}
}
if (pathHasChanged) {
where[paths.join('.')] = where[key]!
delete where[key]
}
}
}