1 | import {SchemaType} from '../parts/Schema'
|
2 | import {SortItem} from '../Sort'
|
3 |
|
4 | const IMPLICIT_FIELDS = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']
|
5 |
|
6 |
|
7 | function 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 |
|
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 |
|
38 | export function getExtendedProjection(schemaType: SchemaType, orderBy: SortItem[]): string {
|
39 | return orderBy.map(ordering => joinReferences(schemaType, ordering.field.split('.'))).join(', ')
|
40 | }
|