-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathget-expand.ts
78 lines (70 loc) · 2.21 KB
/
get-expand.ts
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
import { EntityV4 } from '../entity';
import { Expandable } from '../../common/expandable';
import {
Constructable,
AllFields,
Link,
and,
createGetFilter
} from '../../common';
import { OneToManyLink } from '../../common/selectable/one-to-many-link';
import { getSelectV4 } from './get-select';
import { uriConverterV4 } from './uri-value-converter';
import { oDataUriV4 } from './odata-uri';
function prependDollar(param: string): string {
return `$${param}`;
}
/**
* Get an object containing the given expand as a query parameter, or an empty object if none was given.
*
* @typeparam EntityT - Type of the entity to expand on
* @param expands - The expands to transform to a query parameter
* @param entityConstructor - Constructor type of the entity to expand on
* @returns An object containing the query parameter or an empty object
*/
export function getExpandV4<EntityT extends EntityV4>(
expands: Expandable<EntityT>[] = [],
entityConstructor: Constructable<EntityT>
): Partial<{ expand: string }> {
return expands.length
? {
expand: expands
.map(expand => getExpandAsString(expand, entityConstructor))
.join(',')
}
: {};
}
function getExpandAsString<EntityT extends EntityV4>(
expand: Expandable<EntityT>,
entityConstructor: Constructable<EntityT>
): string {
if (expand instanceof AllFields) {
return '*';
}
let params = {};
if (expand instanceof Link) {
params = {
...params,
...getSelectV4(expand._selects),
...getExpandV4(expand._expand, expand._linkedEntity)
};
if (expand instanceof OneToManyLink) {
params = {
...params,
...createGetFilter(uriConverterV4).getFilter(
and(...expand._filters?.filters),
entityConstructor
),
...(expand._skip && { skip: expand._skip }),
...(expand._top && { top: expand._top }),
...(expand._orderBy && oDataUriV4.getOrderBy(expand._orderBy))
};
}
const subQuery = Object.entries(params)
.map(([key, value]) => `${prependDollar(key)}=${value}`)
.join(';');
const subQueryWithBrackets = subQuery ? `(${subQuery})` : '';
return `${expand._fieldName}${subQueryWithBrackets}`;
}
return '';
}