UNPKG

1.46 kBPlain TextView Raw
1import {SchemaType} from '../parts/Schema'
2import {SortItem} from '../Sort'
3
4const IMPLICIT_FIELDS = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']
5
6// Takes a path array and a schema type and builds a GROQ join every time it enters a reference field
7function joinReferences(schemaType: SchemaType, path: string[]): string {
8 const [head, ...tail] = path
9
10 if (!schemaType.fields) {
11 return ''
12 }
13
14 const schemaField = schemaType.fields.find(field => field.name === head)
15 if (!schemaField) {
16 if (!IMPLICIT_FIELDS.includes(head)) {
17 // eslint-disable-next-line no-console
18 console.warn(
19 'The current ordering config targeted the nonexistent field "%s" on schema type "%s". It should be one of %o',
20 head,
21 schemaType.name,
22 schemaType.fields.map(field => field.name)
23 )
24 }
25 return ''
26 }
27
28 if (schemaField.type.name === 'reference' && schemaField.type.to) {
29 const refTypes = schemaField.type.to
30 return `${head}->{${refTypes.map(refType => joinReferences(refType, tail)).join(',')}}`
31 }
32
33 const tailFields = tail.length > 0 && joinReferences(schemaField.type, tail)
34 const tailWrapper = tailFields ? `{${tailFields}}` : ''
35 return tail.length > 0 ? `${head}${tailWrapper}` : head
36}
37
38export function getExtendedProjection(schemaType: SchemaType, orderBy: SortItem[]): string {
39 return orderBy.map(ordering => joinReferences(schemaType, ordering.field.split('.'))).join(', ')
40}