-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathresponse-data-accessor.ts
79 lines (69 loc) · 2.29 KB
/
response-data-accessor.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
79
import { createLogger } from '@sap-cloud-sdk/util';
import { ResponseDataAccessor } from '../../odata-common';
const logger = createLogger({
package: 'core',
messageContext: 'response-data-accessor'
});
/**
* Methods to extract the data from OData v4 responses.
*/
/**
* Extract the collection data from the response.
* If the data does not contain a collection an empty array is returned.
* @param data - Response of the OData v4 service
* @returns any[] - Collection extracted from the response
*/
export function getCollectionResult(data): any[] {
validateCollectionResult(data);
return isCollectionResult(data) ? data.value : [];
}
/**
* Checks if the data contains a collection result.
* @param data - Response of the OData v4 service
* @returns boolean - true if the data is a collection result
*/
export function isCollectionResult(data): boolean {
return Array.isArray(data.value);
}
function validateCollectionResult(data): void {
if (!isCollectionResult(data)) {
logger.warn(
'The given reponse data does not have the standard OData v4 format for collections.'
);
}
}
/**
* Extract the collection data from the one to many link response.
* If the data does not contain a collection an empty array is returned.
* @param data - Response of the one to many link
* @returns any[] - Collection extracted from the response
*/
export function getLinkedCollectionResult(data): any[] {
return Array.isArray(data) ? data : [];
}
/**
* Extract the single entry data from the response.
* If the data does not contain a single object an empty object is returned.
* @param data - Response of the OData v4 service
* @returns Record<string, any> - single object extracted from the response
*/
export function getSingleResult(data): Record<string, any> {
validateSingleResult(data);
return isSingleResult(data) ? data : {};
}
function isSingleResult(data): boolean {
return typeof data === 'object' && !Array.isArray(data);
}
function validateSingleResult(data): void {
if (!isSingleResult(data)) {
logger.warn(
'The given response data does not have the standard OData v4 format for single results.'
);
}
}
export const responseDataAccessorV4: ResponseDataAccessor = {
getCollectionResult,
getLinkedCollectionResult,
getSingleResult,
isCollectionResult
};