-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathget-expand.ts
50 lines (45 loc) · 1.62 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
/* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. */
import { EntityV2 } from '../entity';
import { Selectable, Link } from '../../common';
/**
* Get an object containing the given expand as a query parameter, or an empty object if none was given.
* In this OData v2 expand, selected properties are automatically added to the expand.
*
* @typeparam EntityT - Type of the entity to expand on
* @param selects - The selects which are expanded if necessary
* @param entityConstructor - Constructor type of the entity to expand on
* @returns An object containing the query parameter or an empty object
*/
export function getExpandV2<EntityT extends EntityV2>(
selects: Selectable<EntityT>[] = []
): Partial<{ expand: string }> {
const expand = getExpandsAsString(selects);
return expand.length ? { expand: expand.join(',') } : {};
}
function getExpandsAsString<EntityT extends EntityV2>(
selectables: Selectable<EntityT>[],
initialExpand: string[] = [],
parent = ''
): string[] {
return selectables.reduce((combination: string[], selectable) => {
const fullFieldName = getPath(parent, selectable._fieldName);
if (selectable instanceof Link) {
combination = [...combination, fullFieldName];
if (selectable._selects.length) {
return getExpandsAsString(
selectable._selects,
combination,
fullFieldName
);
}
}
return combination;
}, initialExpand);
}
function getPath(parent: string, fieldName: string): string {
if (parent) {
return `${parent}/${fieldName}`;
}
return fieldName;
}
export { getExpandV2 as getExpand };