|
| 1 | +import type { FlattenedField } from '../fields/config/types.js' |
| 2 | +import type { Payload, Where } from '../types/index.js' |
| 3 | + |
| 4 | +/** |
| 5 | + * Currently used only for virtual fields linked with relationships |
| 6 | + */ |
| 7 | +export const sanitizeWhereQuery = ({ |
| 8 | + fields, |
| 9 | + payload, |
| 10 | + where, |
| 11 | +}: { |
| 12 | + fields: FlattenedField[] |
| 13 | + payload: Payload |
| 14 | + where: Where |
| 15 | +}) => { |
| 16 | + for (const key in where) { |
| 17 | + const value = where[key] |
| 18 | + |
| 19 | + if (['and', 'or'].includes(key.toLowerCase()) && Array.isArray(value)) { |
| 20 | + for (const where of value) { |
| 21 | + sanitizeWhereQuery({ fields, payload, where }) |
| 22 | + } |
| 23 | + continue |
| 24 | + } |
| 25 | + |
| 26 | + const paths = key.split('.') |
| 27 | + let pathHasChanged = false |
| 28 | + |
| 29 | + let currentFields = fields |
| 30 | + |
| 31 | + for (let i = 0; i < paths.length; i++) { |
| 32 | + const path = paths[i]! |
| 33 | + const field = currentFields.find((each) => each.name === path) |
| 34 | + |
| 35 | + if (!field) { |
| 36 | + break |
| 37 | + } |
| 38 | + |
| 39 | + if ('virtual' in field && field.virtual && typeof field.virtual === 'string') { |
| 40 | + paths[i] = field.virtual |
| 41 | + pathHasChanged = true |
| 42 | + } |
| 43 | + |
| 44 | + if ('flattenedFields' in field) { |
| 45 | + currentFields = field.flattenedFields |
| 46 | + } |
| 47 | + |
| 48 | + if ( |
| 49 | + (field.type === 'relationship' || field.type === 'upload') && |
| 50 | + typeof field.relationTo === 'string' |
| 51 | + ) { |
| 52 | + const relatedCollection = payload.collections[field.relationTo] |
| 53 | + if (relatedCollection) { |
| 54 | + currentFields = relatedCollection.config.flattenedFields |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if (pathHasChanged) { |
| 60 | + where[paths.join('.')] = where[key]! |
| 61 | + delete where[key] |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments